Programmed books 3¶
Summing pages¶
from fpdf import FPDF
Setup¶
pdf = FPDF('P', 'mm', format=(200,210) )
pdf.set_margins(left=10, top=10, right=10)
pdf.set_font('Helvetica')
Title Page¶
pdf.add_page()
pdf.set_font_size(40)
pdf.ln(50)
pdf.multi_cell(185, None, txt='Summing pages', align='C')
False
Summing pages¶
Sum up pages starting with 2.
pdf.set_font_size(30)
calculation = '1' # Stores the calculation.
ln = 135 # Ln adapts to length of calculation.
for page_number in range(2,101):
pdf.add_page()
# reduce ln on 11, 21, 31, ...
if (page_number -1) % 10 == 0:
# reduce line feed
ln -= 15
pdf.ln(ln)
# Add 1.
calculation += ' + 1'
# Add equal sign and result (page_number)
txt = calculation + '\n=\n' + str(page_number)
pdf.multi_cell(w=0, h=15, txt=txt, align='C')
Custom fonts¶
In order to run the code below you’ll need a folder named fonts
in the directory of this notebook. You can download a folder with example fonts here.
from fpdf import FPDF
import os
''' Create FPDF object. '''
pdf = FPDF('L', 'mm', format='A5')
pdf.set_margins(left=20, top=15, right=20)
''' Create a list of available fonts. '''
# Get names of all files in a directory.
fonts = os.listdir('fonts')
# Reduce list to files ending with .ttf
fonts = [font for font in fonts if font.endswith('.ttf')]
''' Render text in different fonts. '''
pdf.add_page()
# Loop through list of fonts.
for font in fonts:
# Extract font name.
font_name = font.removesuffix('.ttf')
font_path = 'fonts/' + font
txt = 'The quick brown fox jumps over the lazy dog.'
# Append font name to the text.
txt += '\n(' + font_name + ')'
# Add font to FPDF.
pdf.add_font(font_name, '', font_path, uni=True)
pdf.set_font(font_name)
pdf.set_font_size(14)
# Add text with that font.
pdf.multi_cell(w=0, h=7, txt=txt, align='L')
pdf.ln(5)
''' Save PDF. '''
filename = 'generated_pdfs/005.pdf'
pdf.output(filename)
Read and print itself¶
The following code reads itself and prints that code to a PDF.
It works only if executed as a Python file like
python3 006.py # if the code is saved as 006.py
, not as a Jupyter Notebook!
006.py:
from fpdf import FPDF
import sys
''' Create FPDF object. '''
pdf = FPDF('P', 'mm', format='A5')
pdf.set_margins(left=20, top=30, right=20)
pdf.set_font('Courier', size=10)
''' Print code. '''
# Get the name of this Python file.
filename = sys.argv[0]
# Read this file.
with open(filename) as f:
txt = f.read()
pdf.add_page()
pdf.multi_cell(0, None, txt=txt)
''' Save PDF. '''
filename = filename.replace('.py', '.pdf')
pdf.output('generated_pdfs/' + filename)