First book

Recommendation: Write the code in a Python file (a plain text file with the file ending .py) instead of working inside the Jupyter Notebook. (See the chapter Programs are text (files) from the previous chapter.)

Setup

First we have to install the library fpdf. A library is additional code that we can use for our program. It’s like an extension to the built-in functionality of a programming language.

Unfortunately fpdf it is not available through the conda package manager, so we have to use the default python package installer pip.

The following instructions are from this post: https://stackoverflow.com/a/43729857

First install pip with conda:

conda activate name_of_your_environment

conda install pip

Next we will explicitly use this pip version to install the required library:

# Get the location of your environment:
conda env list

This returns for example:

base                     /home/username/miniconda3
pbwp                  *  /home/username/miniconda3/envs/pbwp

The environment with * is the active environment.

To call pip inside this environment, we have to add /bin/pip to the path.

The command looks like this:

miniconda3/envs/pbwp/bin/pip install fpdf2

Documentation of fpdf2

Import library

from fpdf import FPDF

Create an FPDF object

Next we will create an object which holds all the data of our PDF. Furthermore this object has built-in methods which help us define and create our PDF.

pdf = FPDF('P', 'mm', format='A5')

From the documentation:

By default, a FPDF document has a A4 format with portrait orientation.

Other formats & orientation can be specified to FPDF constructor:

pdf = fpdf.FPDF(orientation=”landscape”, format=”A5”)

Currently supported formats are a3, a4, a5, letter, legal or a tuple (width, height). Additional standard formats are welcome and can be suggested through pull requests.

Create content in/ with this object

First we have to add an empty page to our FPDF object:

# Add an empty page.
pdf.add_page()

Before we can add text, we have to define a font and a font size:
# Set a font and font size.
pdf.set_font('Courier') # Standard fonts: Courier, Helvetica & Times.
pdf.set_font_size(11)

We'll use a text field called multi-cell to insert text.
The method multi-cell takes several arguments which define the field and its content:
  • w = cell width. If 0, they extend up to the right margin of the page.

  • h = cell height. Default value: None, meaning to use the current font size.

  • txt = string (text) to print.

# Add a text field.
pdf.multi_cell(w=0, h=None, txt='My first programmed PDF.')
False

Export PDF

First we will create a subfolder inside the folder where this code is stored. The name + / of the folder is stored in the variable called path below.

path = 'generated_pdfs/' # Make sure to create the specific folder in advance.
filename = '001.pdf'
pdf.output(path + filename)

Result

View PDF

001.png