Almost everyone is talking about Python nowadays and it is not for fun that this is happening. Python as a programming language has a lot of use cases and many of these use cases are even less known to many people.
In this tutorial, we will look at how to use Python to create a PDF and also how to customize the PDF that we generate with Python. If you are interested in learning this use case of Python then keep reading.
Step-by-Step Guide to Generate PDFs with Python
1. Setting Things Up
To be able to follow the rest of the tutorial,, you will need to have Python installed on the computer or device you are using. If you are yet to install it, then go ahead and download Python from python.org. Double click on the installer file that you download to start the installation process.
Tip: During installation, ensure you check the box that says “Add Python to PATH” for easy access.
2. Installing the Required Library
Python uses libraries (collections of functions) to extend its capabilities. For PDF generation, we’ll use the `fpdf` library. To use it, we will first need to install that library. Follow the steps below to install this library.
Open your computer’s command line or terminal and type:
pip install fpdf
3. Creating Your First PDF
Let’s dive right in and generate a basic PDF. To create a PDF with the FPDF library, you have to start off by importing the library so you have access to all its functions. Then proceed to create an instance of the imported module.
You can then go on to create a page with the `add_page()` method. You can also set the font with the `set_font()` method. To add a cell of content to the PDF, you can use the `cell()` method. You can call the `output()` method to save the PDF file that was generated.
Now, let’s put all of this knowledge into practice.
a. Create a new file named `generate_pdf.py`.
b. Copy and paste the following code:
from fpdf import FPDF # Create instance of FPDF class pdf = FPDF() # Add a page pdf.add_page() # Set font pdf.set_font("Arial", size = 12) # Add a cell pdf.cell(200, 10, txt = "Hello, welcome to PDF generation with Python!", ln = True, align = 'C') # Save the pdf with name .pdf pdf.output("Greeting.pdf")
c. Run the script:
python generate_pdf.py
Result: You should see a file named `Greeting.pdf` in the same directory as your script.
Customizing Your PDF
Once you’re comfortable with the basics, you can customize your PDFs further.
Headers and Footers: Add consistent headers or footers to your pages.
Images: Embed images to make your PDFs visually appealing.
Tables: Display structured data.
(Note: Each of these customizations can be achieved using methods available in the fpdf library. Check out the official documentation for more details.)
Let’s put this into practice by writing code to generate a PDF with some of the above mentioned customization.
Adding a Header and Footer
Headers and footers are useful for adding consistent information on every page of your PDF, like the document title or page numbers.
Let’s modify the previous PDF generating script that we wrote `generate_pdf.py` to include header and footer methods:
from fpdf import FPDF class PDF(FPDF): def header(self): self.set_font('Arial', 'B', 12) self.cell(0, 10, 'My Customized PDF By LearninBits', 0, 1, 'C') def footer(self): self.set_y(-15) self.set_font('Arial', 'I', 8) self.cell(0, 10, 'Page ' + str(self.page_no()), 0, 0, 'C') pdf = PDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(0, 10, "This document now has a header and footer!", ln=True, align='C')
Embedding an Image
You can add images to make your PDF more visually appealing. Add the following lines to your generate_pdf.py script to embed an image:
# Ensure you have an image named 'sample.jpg' in the same directory or change that to the exact name of the image you want to embed pdf.image('sample.jpg', x=10, y=40, w=190)
Inserting a Table
Tables are crucial for displaying structured data and are common elements in various documents. Let’s see how we can insert a table in the PDF that we create.
Append the following code to generate_pdf.py to add a table:
# Column headers headers = ['Name', 'Age', 'City'] # Sample data data = [['Alice', '24', 'New York'], ['Bob', '28', 'Los Angeles'], ['Charlie', '30', 'Chicago']] # Setting column width col_width = pdf.get_string_width(max(headers, key=lambda s: len(s))) + 6 # Printing headers for header in headers: pdf.cell(col_width, 10, header, 1) pdf.ln() # Move to the next line # Printing data for row in data: for item in row: pdf.cell(col_width, 10, item, 1) pdf.ln()
Finally, save the PDF:
pdf.output("Customized_PDF.pdf")
Run your generate_pdf.py script:
python generate_pdf.py
Result: You should now have a “Customized_PDF.pdf” file in the same directory as your script, complete with a header, footer, image, and table.
This practical example provides an overview of customizing PDFs using Python. With the fpdf library, the possibilities are vast, and with a bit of practice, you can generate complex and professional-looking documents.
This tutorial on customizing PDFs is just a glimpse of what you can achieve with Python. If you’ve found this guide helpful, we have a plethora of other wonderful tutorials that cater to both beginners and experienced developers alike.
🌟 Don’t miss out on our latest updates and insightful tutorials. Follow us on Twitter and stay updated with the best of Python and more!
Happy coding, and see you in our next tutorial!