Convert Python File to PDF
Last Updated :
14 Apr, 2025
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.
Similar Reads
Python Convert Html to PDF
Convert HTML/webpage to PDF There are many websites that do not allow to download the content in form of pdf, they either ask to buy their premium version or don't have such download service in form of pdf. Conversion in 3 Steps from Webpage/HTML to PDF Step1: Download library pdfkit $ pip install p
1 min read
Convert PDF to Image using Python
Many tools are available on the internet for converting a PDF to an image. In this article, we are going to write code for converting pdf to image and make a handy application in python. Before writing the code we need to install the required module pdf2image and poppler. Modules Neededpdf2image 1.1
2 min read
Convert Excel to PDF Using Python
Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. In this article, we will learn how to convert an
2 min read
Convert PDF to CSV using Python
Python is a high-level, general-purpose, and very popular programming language. Python programming language (the latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python Programming Language is very well sui
2 min read
How to Convert Image to PDF in Python?
img2pdf is an open source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance image (Brightness, contrast and other things) Use this command to install the packages pip install img2pdf Below is the implementation: Image can be converted
1 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Do
3 min read
TIFF to PDF Converter
In today's digital world, efficient file conversion tools are essential for managing and sharing various document formats. TIFF (Tagged Image File Format) is commonly used for storing high-quality images, but it's not always the most convenient format for sharing or archiving multiple images. iframe
6 min read
How to Crack PDF Files in Python?
Prerequisite: tqdm In this article, we will learn How to Crack a Protected PDF File Using Python. Here we will use the Brute force Method, to Crack a PDF File using pikepdf module in Python. Required Modules : pikepdf is a Python module, which is used to create, manipulate, and repair PDF Files.pip
2 min read
Convert Images to PDFs using Tkinter - Python
Prerequisite: Tkinter, img2pdf Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easie
3 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Con
3 min read