Create a PDF using fpdf in Python
Hello friends, in this tutorial I will tell you how you can create a PDF file using fpdf package in Python. The tutorial will contain the following :
- Installation of the fpdf package.
- Import the package.
- Create a pdf .
Installation of the fpdf package
Firstly, I have to install the package as it is a third-party module. To install, open your command prompt in Windows or Terminal in macOS/ Linux, and execute the following command.
pip install fpdf
Import the package
Once installed, I have imported the package to enable usage. To import, write the following command in your code. As I only need the FDPF module from the package, I have curated the import statement accordingly.
from fpdf import FPDF
Create a PDF using fpdf in Python
The first thing, I have done is to create an object of the FPDF class and store it in a temporary variable, pdf_file
. Now that I have a file, I need a page to write on, which is why I have used the add_page()
function. Using the set_font()
function I have passed the font type as Arial and font size equal to 15 as an argument. Now that I have defined the font size as well as type, I need to write on the file. I have used the cell()
function, to write on the PDF file. The function takes the width, height, text, and line number as arguments. In this example, I have defined width as 200, height as 10, txt as 'This is Codespeedy'
, and ln as 1.
Code :
pdf_file = FPDF() pdf_file.add_page() pdf_file.set_font("Arial", size = 15) pdf_file.cell(200, 10, txt = "This is Codespeedy.", ln = 1) pdf_file.output("sample.pdf")
After the contents have been written to the file, using the output()
function I have saved the pdf file as sample.pdf
.
Output :
Thus I have successfully created a PDF using fpdf in Python.
Leave a Reply