1

I am trying to create table of contents using Python's FPDF package (https://pyfpdf.readthedocs.io/en/latest/)

I want the table of contents to be at the top of the PDF document, and clickable so that the reader is instantly taken to a section.

The issue I have is that for the links to work, the table of contents needs to be at the end of the document.

I have tried using python's PyPDF2 to split the created PDF document and move the table of contents to the beginning of the document. The problem is that in the resulting PDF the links no longer work.

I am using python (v3.7) with Spyder.

Here is my code for creating the table of contents:

from fpdf import FPDF

# This is my section with link to table of contents
report.add_page(orientation='p')
report.set_font('Helvetica', size=22, style ='B')
report.cell(200, 10, 'section', 0, 2, 'l') 
DD = report.add_link()
report.set_link(DD)

# Table of contents including that one section
report.write(5, 'Section',DD) 

Here is my code for rearranging the PDF document (TOC = table of contents):

from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger

PDF_report = PdfFileReader('file.pdf')
pdf_bulk_writer = PdfFileWriter()
output_filename_bulk = "bulk.pdf"
pdf_TOC_writer = PdfFileWriter()

output_filename_TOC = "TOC.pdf"

for page in range(PDF_report.getNumPages()):
    current_page = PDF_report.getPage(page)
    if page == PDF_report.getNumPages()-1:
        pdf_TOC_writer.addPage(current_page)
    if page <= PDF_report.getNumPages()-2:
        pdf_bulk_writer.addPage(current_page)

# Write the data to disk
with open(output_filename_TOC, "wb") as out:
     pdf_TOC_writer.write(out)
     print("created", output_filename_TOC)       

# Write the data to disk
with open(output_filename_bulk, "wb") as out:
     pdf_bulk_writer.write(out)
     print("created", output_filename_bulk)   

pdfs = ['TOC.pdf', 'bulk.pdf']

merger = PdfFileMerger()

for pdf in pdfs:
    merger.append(pdf)

merger.write("result.pdf")
merger.close()
UpperEastSide
  • 117
  • 1
  • 16
  • Take a look at a similar question https://stackoverflow.com/questions/6157456/create-outlines-toc-for-existing-pdf-in-python – Kate Orlova Jun 15 '20 at 18:18

0 Answers0