Create PDF file from .txt file in Python
In this tutorial, we are going to discuss about how to create a pdf file from a .txt file in Python. We are going to do this using fpdf package. fpdf package is basically a package that is used to make a pdf file. If you have already installed fpdf then you can ignore the next step otherwise see how you can install fpdf in your machine.
Installation of fpdf
If you have windows machine then go to the command prompt or if you have Linux or Mac then go to terminal and write the following code to install fpdf,
pip install fpdf
How to create PDF file from .txt file in Python
So, our first step is to import the fpdf and os module. We import FPDF from fpdf as fp to make the code easy to write.
from fpdf import FPDF as fp import os
Our next step is to consider a variable. We consider it as file1 and using this variable we are going to open the .txt file. In this case, we are using open() function. In the first argument, we are giving the location and name of the file (if .txt and python file has the same location then only the name of the file has to write) and in the next argument, we are giving “r+” to read the file.
file1 = open("myfile.txt","r+")
Then we have to split the lines as to look our pdf better. So, in this case, we are going to use .split() function to split the lines.
After this, we take a variable for .fp() function and then we have to add a page by using .add_page() function. Next, we set the font by .set_font() function. The function takes two arguments first is the font and then it’s size.
txtPdf=fp() txtPdf.add_page() txtPdf.set_font("Roboto",size=14)
Thereafter we take a variable ct to store the page count. Now it’s time to write the pdf. We write the pdf using .cell() function. The function takes five arguments first margins then the text then line no. then align. To write the whole text we are going to use a for a loop. The for loop runs until the last line of paragraph (.txt file’s text).
ct=1 for para in paragraph: txtPdf.cell(200,10,txt=paragraph,ln=ct,align="C") ct+=1
At last, it’s time to get output. So we are using .output() function.
The whole code of the above explanation is shown below
from fpdf import FPDF as fp import os file1 = open("myfile.txt","r+") paragraph=file1.split("\n") txtPdf=fp() txtPdf.add_page() txtPdf.set_font("Roboto",size=14) ct=1 for para in paragraph: txtPdf.cell(200,10,txt=paragraph,ln=ct,align="C") ct+=1 txtPdf.output()