The Wayback Machine - https://web.archive.org/web/20240527035129/https://www.geeksforgeeks.org/convert-python-file-to-pdf/
Open In App

Convert Python File to PDF

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a versatile programming language widely used for scripting, automation, and web development. Occasionally, you might find the need to convert your Python code into a more accessible format, such as a PDF. In this article, we will explore some methods to achieve this conversion using different libraries: ReportLab, FPDF, and Matplotlib.

How To Convert A Python File To A Pdf?

Below, are the method To Convert A Python File To A Pdf in Python.

Convert A Python File To A Pdf Using ReportLab

ReportLab is a powerful Python library for creating PDF documents. First, install the ReportLab to convert a Python file to a PDF using the below command

pip install reportlab

In this example, below code uses the ReportLab library to convert a Python file (‘example.py‘) to a PDF (‘output_reportlab.pdf’). It creates a canvas for the PDF, reads the content of the Python file, and writes it to the PDF at coordinates (100, 800). Finally, the PDF is saved, resulting in a PDF document containing the Python code.

Python3




from reportlab.pdfgen import canvas
 
def convert_to_pdf_reportlab(input_file, output_pdf):
    pdf_canvas = canvas.Canvas(output_pdf)
 
    with open(input_file, 'r') as python_file:
        content = python_file.read()
        pdf_canvas.drawString(100, 800, content)
 
    pdf_canvas.save()
 
# Example usage:
convert_to_pdf_reportlab('example.py', 'output_reportlab.pdf')
print("PDF is Saved Successfully")


Output :

PDF is Saved Successfully

Convert A Python File To A Pdf Using FPDF

FPDF is a lightweight PDF generation library for Python. Here’s how you can use FPDF to convert a Python file first install it using below command:

pip install fpdf

In this example, below code utilizes the FPDF library to convert a Python file (‘example.py’) into a PDF (‘output_fpdf.pdf’). It creates a PDF document, adds a page, and sets the font. The content of the Python file is then read and inserted into the PDF with line breaks using `multi_cell`. Finally, the resulting PDF is saved, containing the formatted Python code.

Python3




from fpdf import FPDF
 
def convert_to_pdf_fpdf(input_file, output_pdf):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
 
    with open(input_file, 'r') as python_file:
        content = python_file.read()
        pdf.multi_cell(0, 10, content)
 
    pdf.output(output_pdf)
 
# Example usage:
convert_to_pdf_fpdf('example.py', 'output_fpdf.pdf')
print("PDF is Saved Successfully")


Output :

PDF is Saved Successfully

Convert A Python File To A Pdf Using Matplotlib

Matplotlib is primarily a data visualization library, but it can also be used to convert text into a PDF. first install it.

pip install matplotlib

In this example, below code utilizes the Matplotlib library to convert a Python file (‘example.py’) into a PDF (‘output_matplotlib.pdf’). It reads the content of the Python file, creates a Matplotlib figure with a text element, and saves it as a PDF with no axes. The resulting PDF contains the Python code with the specified formatting.

Python3




import matplotlib.pyplot as plt
 
def convert_to_pdf_matplotlib(input_file, output_pdf):
    with open(input_file, 'r') as python_file:
        content = python_file.read()
        fig, ax = plt.subplots()
        ax.text(0.1, 0.5, content, wrap=True, fontsize=12)
        ax.axis('off')
 
        plt.savefig(output_pdf, format='pdf')
 
# Example usage:
convert_to_pdf_matplotlib('example.py', 'output_matplotlib.pdf')
print("PDF is Saved Successfully")


Output :

PDF is Saved Successfully

Video Demonstration



Similar Reads

How to convert PDF file to Excel file using Python?
In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It's a simple web-based API, so can be called from any programmin
2 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. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to convert a PDF file to TIFF file using Python?
This article will discover how to transform a PDF (Portable Document Format) file on your local drive into a TIFF (Tag Image File Format) file at the specified location. We'll employ Python's Aspose-Words package for this task. The aspose-words library will be used to convert a PDF file to a TIFF file. Aspose-Words: Aspose-Words for Python is a pot
3 min read
Send PDF File through Email using pdf-mail module
pdf_mail module is that library of Python which helps you to send pdf documents through your Gmail account. Installing Library This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install pdf-mail Function of pdf_mail This module only comes with a singl
2 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 Document Format) is one of the basic requirements in
3 min read
Convert PDF File Text to Audio Speech using Python
Let us see how to read a PDF that is converting a textual PDF file into audio. Packages Used: pyttsx3: It is a Python library for Text to Speech. It has many functions which will help the machine to communicate with us. It will help the machine to speak to usPyPDF2: It will help to the text from the PDF. A Pure-Python library built as a PDF toolkit
2 min read
Convert PDF to TXT File Using Python
As the modern world gets digitalized, it is more and more necessary to extract text from PDF documents for purposes such as data analysis or content processing. There is a versatile ecosystem of Python libraries that can work with different file formats including PDFs. In this article, we will show how to build a simple PDF-to-text converter in Pyt
2 min read
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
Save multiple matplotlib figures in single PDF file using Python
In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
3 min read