In this tutorial, I am going to Create PDF from .txt file in Python using FPDF which is a Python library, ‘PyFPDF’ is a library for PDF document generation under Python, ported from PHP that can be used for create and manipulate PDF documents programmatically.
Requirements
- FPDF
To get started make sure you have FPDF installed in your system. If you don’t have these you have to install them using PIP which is a package manager for Python that can install Python modules or packages.
Using these following commands you can install FPDF in your system
pip install fpdf
Code
Here in this code I am going to save FPDF() into a variable and add page using add_page() function, then set style and size of font in the pdf using set_font() function and open the text file to read mode in python using open() function, then the insert texts into the pdf using the cell()function, After that save the pdf using output() function.
#importing modules from fpdf import FPDF # save FPDF() into a variable pdf_open = FPDF() # Add a Page pdf_open.add_page() # Set style and size of font in the pdf pdf_open.set_font("Arial",size=12) # open the text file to read pdf = open("I AM2.txt","r") # insert the texts in pdf for n in pdf : pdf_open.cell(200,10,txt = n , ln = 1,align = 'c') # save the pdf pdf_open.output("I AM2.pdf")
Output
Before :
After :
After executing the code .txt file of the provided text is generated to .pdf