In this article, you’ll learn how to create your own customized PDF using a module called PyFPDF. According to the official documentation, PyFPDF is

It offers the following features:

  • Python 2.7 to 3.5 support.
  • Unicode (UTF-8) TrueType font subset embedding.
  • Internal/external links.
  • PNG, GIF, and JPG support (including transparency and alpha channel).
  • Shape, line drawing.
  • Cell/Multi-cell/Plaintext writing, automatic page breaks.
  • Basic html2pdf (Templates with a visual designer in the works).
  • Exceptions support, other minor fixes, improvements, and PEP8 code cleanups
  • Tox tests.

Let’s start installing the necessary modules.


1. Setup

Install from PyPI

You can easily install it using pip install. For this tutorial, I’m installing the forked version of the original PyFPDF with the following command:

pip install fpdf2

If you’re looking for the original version, install it with the following command instead:

pip install fpdf

You can clone the repository and install it directly on your local machine. It requires additional dependencies such as Pillow if you’re installing it this way.

In the next section, we’re going to explore some of the features and functions available in this module.

Basic Usage

Import

Let’s start by adding the following import statement in your Python file.

from fpdf import FPDF

Instance of FPDF

The next step is to initialize an instance of FPDF which is the class constructor. It accepts the following input parameters:

fpdf = FPDF(orientation = 'P', unit = 'mm', format='A4')
  • orientation: Default page orientation. Possible values are (case insensitive) P or L. The default value is P.
  • unit: User unit. Possible values are ptmmcmin. The default value is mm.
  • format: The format used for pages. It can be any one of the following values (case insensitive): A3A4A5LetterLegal or a tuple containing the width and height. The default value is A4.

You can initialize it as a blank constructor. However, please bear in mind the unit is mm, not point. If you’re dealing with images, the dimensions are usually expressed in points instead. Modify according to your use cases.

fpdf = FPDF()

#python #devops #programming #pdf

How to Create a PDF in Python
18.85 GEEK