Hello, readers! In this article, we will be focusing on Python fpdf module in detail.
So, let us begin!! 🙂
The Python fpdf module – Quick Overview
Python offers us fpdf module that enables us to have data in PDF format without having to do much.
The fpdf module offers us various in-built functions to convert text files as well as text data into PDF files. This is helpful especially when we want to represent the output of certain computations in a PDF format directly by the execution of the script.
By this, we automate the entire process of conversion of data into a PDF format without having to worry about the storage path/location, compatibility of the extension, etc. Because with fpdf module, we can even have the converted PDF file at the local storage or to a VM or even to a public cloud platform.
In the context of this topic, we will be having a look at the below functions offered by the Python fpdf module–
- Conversion of text data into a PDF form
- Conversion of text files into a PDF
1. Converting text files to PDF using fpdf module
With Python fpdf module, we can convert the files with .txt extensions i.e. text files into a PDF format easily with fpdf.output() function.
We need to follow the series of below steps to achieve the same–
- Open the text file with file.open() function in read mode.
- Further, we need to traverse the data of every row using cell() function and simultaneously get it ready for storage into a PDF format.
- Finally, use fpdf.output() function to represent the traversed data into a PDF format at the specified location.
from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size = 25) # create a cell file = open("C:/Users/HP/OneDrive/Desktop/data.txt", "r") # insert the texts in pdf for g in file: pdf.cell(200, 10, txt = g, ln = 1, align = 'C') pdf.output("op.pdf")
2. Converting text data into a PDF format
Apart from converting the .txt files into a PDF format, we can also convert the raw text data directly into a PDF form. On similar lines to the .txt conversion to .pdf, here we give raw text data as input and convert it into PDF format.
- Import the FPDF module. Use add_page() function, to have a white page for us to imprint the data on.
- Create a cell using cell() function and pass the raw text data to it.
- We can create multiple such cells with text data through step 2.
- Use fpdf.output() function to have all the text data into the PDF format line by line.
from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size = 25) # create a cell pdf.cell(200, 10, txt = "Technologies", ln = 1, align = 'C') pdf.cell(200, 10, txt = "Come, learn Python with us!", ln = 2, align = 'C') pdf.output("info.pdf")
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question. For more such posts related to Python Programming, Stay tuned with us.
Till then, Happy Learning!! 🙂