Welcome folks today in this blog post we will be looking at how to convert raw text and text file to pdf
in python using fpdf
library. All the full source code of the application is given below.
Get Started
In order to get started you need to install fpdf
library inside your python project by executing the pip
command which is shown below
pip install fpdf
After installing this library just create an app.py
file and copy paste the following code
Now we will be converting raw text to pdf
using this snippet of code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Python program to create # a pdf file from fpdf import FPDF # save FPDF() class into a # variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size = 15) # create a cell pdf.cell(200, 10, txt = "GeeksforGeeks", ln = 1, align = 'C') # add another cell pdf.cell(200, 10, txt = "A Computer Science portal for geeks.", ln = 2, align = 'C') # save the pdf with name .pdf pdf.output("GFG.pdf") |
Here in this block of code we are importing the library fpdf
and then we are providing the raw input text
and then we are converting to output pdf file. After this you just need to run the python
application by running the below command
python app.py
As you can see the output pdf file is containing the raw input text
which was provided in the input python script.
Now we will be converting text file
text to output pdf
file and then just copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Python program to convert # text file to pdf file from fpdf import FPDF # save FPDF() class into # a variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size = 15) # open the text file in read mode f = open("myfile.txt", "r") # insert the texts in pdf for x in f: pdf.cell(200, 10, txt = x, ln = 1, align = 'C') # save the pdf with name .pdf pdf.output("mygfg.pdf") |
Now if you execute this python script you will see this text file
which will be converted to pdf file
Now this will be converted to pdf file
like this