HOW #4 – Generate PDFs automatically

Bored from repetitive creation of the same documents? Ease your life with Python and fpdf2 library and let them do automatic work.

Are you bored from repetitive creation of the same documents each day/week/month? With python and fpdf2 library you can create the script which will do it for you!

Today, I will demonstrate such a simple document generation, so you could try it by yourself.

First, I will use FPDF2 library: https://pypi.org/project/fpdf2/

Install it by running command in shell:

pip install fpdf2

Create new empty python file and import libraries:

import rand
from fpdf import FP
from datetime import datetime

I need some sample text data to be the document created of (notice, that two-dimensional array could be easily generated by one line in python):

heading = "DOCUMENT NAM
base_text = [f"Some example text {i}" for i in range(5
table_headline = [f"Column {i}" for i in range(5
tabular_data_2d = \
[[str(random.randint(0, 500)) for i in range(5)] for j in range(40)]

Init the document:

pdf = FPDF
pdf.set_margin(2
pdf.add_page()

This code is self explanatory:

# Setting font: helvetica bold 15
pdf.set_font("courier", "B", 15)

# Moving cursor to the right (in order to have the heading centerred):
pdf.cell(pdf.epw / 2 - 67)

# Printing title:
pdf.cell(134, 10, heading, 1, 0, "C")

# Performing a line break:
pdf.ln(40)

Insert date and time and line break:

pdf.set_font(size=1
pdf.cell(0, 7, f"Date: {datetime.strftime(datetime.now(), '%m/%d/%Y')}", 0,
pdf.cell(0, 7, f"Time: {datetime.strftime(datetime.now(), '%H:%M:%S')}", 0,
pdf.ln(7)

Insert some other text in loop:

for base_text_row in base_tex
pdf.cell(0, 7, base_text_row, 0,
pdf.ln(7)

I will create the table, which can be displayed on more pages. When the table reaches new page, script will generate also table header. or this, I will write function, which will create table header:

def render_table_header(table_col_names, column_width, line_height_
pdf.set_font(size=11, style="B") # enabling bold te
for col_name in table_col_name
pdf.cell(column_width, line_height_, col_name, border=
pdf.ln(line_height
pdf.set_font(style="", size=10) # disabling bold text

I will start the table by calling:

line_height = pdf.font_size *
col_width = pdf.epw / 5 # distribute content even
render_table_header(table_headline, col_width, line_height)

Generate the table (if there is page break, create also table header):

for row in tabular_data_2
if pdf.will_page_break(line_height
render_table_header(table_headline, col_width, line_heigh
for cell in ro
pdf.cell(col_width, line_height, cell, border=
pdf.ln(line_height)

My document is now finished. Lets save it:

pdf.output("report.pdf")

The documentation of FPDF2 library:

https://pyfpdf.github.io/fpdf2/index.html


That's all for today, and I hope you will have a good one.

 

Anton Hajdu