Open In App

Convert Python File to PDF

Last Updated : 14 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are tasked with converting a Python file into a PDF document. This allows you to present or store your Python code in a more accessible format. By converting the code to a PDF, you can easily share or archive it, making it more convenient to view and print in a professional, well-organized manner. Let's understand different methods to do this efficiently, offering flexibility and ease of use while achieving the desired output.

Using ReportLab

ReportLab is a powerful library used to create PDFs in Python. It allows you to customize the layout and format of the content, making it ideal for more advanced use cases. With ReportLab, you can easily convert Python files into PDFs while maintaining control over the design.

Python
from reportlab.pdfgen import canvas

inp = 'example.py'  # input file
out = 'output.pdf'  # output pdf file

# Create PDF canvas
pdf = canvas.Canvas(out)

with open(inp, 'r') as f:
    pdf.drawString(100, 800, f.read())

pdf.save()

print("PDF is Saved Successfully")

Output

PDF is Saved Successfully

Explanation: This code opens the Python file, reads its content and places it on the PDF at coordinates (100, 800) using drawString. After adding the content, it calls save() to generate the PDF.

Using FPDF

FPDF is a lightweight PDF creation library for Python. It is easy to use and perfect for generating PDFs from text-based content. FPDF allows you to add pages, set fonts and manage page formatting. It’s a quick solution for converting Python code into a basic PDF document.

Python
from fpdf import FPDF

inp = 'example.py'     # input file
out = 'output.pdf'     # output pdf file

# Create PDF instance
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)

with open(inp, 'r') as f:
    txt = f.read()
    pdf.multi_cell(0, 10, txt)

pdf.output(out)

print("PDF is Saved Successfully")

Output

PDF is Saved Successfully

Explanation: This code creates a PDF object and adds a page. It then sets the font to Arial, size 12. The Python file is opened, its content is read and written to the PDF using multi_cell to handle line breaks. Finally, the PDF is saved with the specified filename.

Using Matplotlib

While Matplotlib is primarily a plotting library, it can also be used to convert text, including Python code, into a PDF. By creating a figure with the content and saving it as a PDF, this method offers a visual way to present your code. Matplotlib allows you to customize the formatting and style as needed.

Python
import matplotlib.pyplot as plt

inp = 'example.py'      # input file
out = 'output.pdf'      # output pdf file

with open(inp, 'r') as f:
    txt = f.read()
    fig, ax = plt.subplots()
    ax.text(0.1, 0.5, txt, wrap=True, fontsize=12)  # display text in plot
    ax.axis('off')  # hide axes

    plt.savefig(out, format='pdf')  

print("PDF is Saved Successfully")

Output

PDF is Saved Successfully

Explanation: This code reads the content of a Python file, creates a Matplotlib figure, and adds the content as text to the figure. It disables the axis and saves the figure as a PDF.

Using PyPDF2

If you already have a Python code snippet in a PDF or need to merge multiple PDFs, PyPDF2 can help. It’s not used directly to create a PDF from text, but it is useful for combining, splitting, or modifying existing PDF documents. PyPDF2 is ideal for working with PDFs after they have been generated by other methods.

Python
from PyPDF2 import PdfMerger

files = ['output_reportlab.pdf', 'output_fpdf.pdf']  # list of PDFs
out = 'merged.pdf'  # output file

# Merge PDFs
merger = PdfMerger()
for f in files:
    merger.append(f)

merger.write(out)
merger.close()

print("Merged PDF is Saved Successfully")

Output

Merged PDF is Saved Successfully

Explanation: This code creates a PdfMerger object, appends multiple PDFs (from files) into a single merged PDF, saves it with the specified output filename.


Next Article

Similar Reads