- The structuring_pdf.py script is available in GitHub here: https://github.com/PacktPublishing/Python-Automation-Cookbook/blob/master/Chapter05/structuring_pdf.py. The most relevant bits are displayed here:
import fpdf
from random import randint
class StructuredPDF(fpdf.FPDF):
LINE_HEIGHT = 5
def footer(self):
self.set_y(-15)
self.set_font('Times', 'I', 8)
page_number = 'Page {number}/{{nb}}'.format(number=self.page_no())
self.cell(0, self.LINE_HEIGHT, page_number, 0, 0, 'R')
def chapter(self, title, paragraphs):
self.add_page()
link = self.title_text(title)
page = self.page_no()
for paragraph in paragraphs:
self.multi_cell(0, self.LINE_HEIGHT, paragraph)
self.ln()
return link, page
def title_text(self, title):
self.set_font('Times', 'B', 15)
self.cell(0, self.LINE_HEIGHT, title)
self.set_font('Times', '', 12)
self.line(10, 17, 110, 17)
link = self.add_link()
self.set_link(link)
self.ln()
self.ln()
return link
def get_full_line(self, head, tail, fill):
...
def toc(self, links):
self.add_page()
self.title_text('Table of contents')
self.set_font('Times', 'I', 12)
for title, page, link in links:
line = self.get_full_line(title, page, '.')
self.cell(0, self.LINE_HEIGHT, line, link=link)
self.ln()
LOREM_IPSUM = ...
def main():
document = StructuredPDF()
document.alias_nb_pages()
links = []
num_chapters = randint(5, 40)
for index in range(1, num_chapters):
chapter_title = 'Chapter {}'.format(index)
num_paragraphs = randint(10, 15)
link, page = document.chapter(chapter_title,
[LOREM_IPSUM] * num_paragraphs)
links.append((chapter_title, page, link))
document.toc(links)
document.output('report.pdf')
- Run the script, and it will generate the report.pdf file, which contains some chapters and a table of contents. Note that it generates some randomness, so the specific numbers will vary each time you run it:
$ python3 structuring_pdf.py
- Check the result. Here is a sample:
Check the table of contents at the end: