Python 3 FPDF Library Example to Convert Raw Text and Text File to PDF Full Tutorial For Beginners

Python 3 FPDF Library Example to Convert Raw Text and Text File to PDF Full Tutorial For Beginners

 

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

 

 

# 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

See also  Python 3 Script to Create Excel Sheet or Spreadsheet and Add Rows & Columns Using Google Sheets API Full Project For Beginners

 

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

 

 

 

# 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

 

 

 

 

See also  Python 3 PyQt5 Script to Build Arithmetic Calculator GUI App Full Project For Beginners

Now this will be converted to pdf file like this

 

 

 

 

Leave a Reply