import PyPDF2 def createpdfwithtableofcontents(): Create a new PDF file outputpdf =…
- User
import PyPDF2
def create_pdf_with_table_of_contents(): # Create a new PDF file output_pdf = PyPDF2.PdfWriter()
# Create a page with some content (just an example) page_content = "This is page 1" page = PyPDF2.pdf.PageObject.createBlankPage(width=612, height=792) # Standard letter size in points (8.5 x 11 inches) page.merge_page(PyPDF2.pdf.PageObject.create_text_object(page_content)) # Add the page to the PDF writer output_pdf.add_page(page) # Define the titles and their respective page numbers titles = ["Title 1", "Title 2", "Title 3"] page_numbers = [1, 1, 1] # Adjust with actual page numbers # Create a table of contents (TOC) toc_page = PyPDF2.pdf.PageObject.createBlankPage(width=612, height=792) # New blank page for TOC toc_content = "Table of Contents:\n\n" for title, page_num in zip(titles, page_numbers): toc_content += f"- {title} (Page {page_num})\n" toc_page.merge_page(PyPDF2.pdf.PageObject.create_text_object(toc_content)) output_pdf.add_page(toc_page) # Add internal links to the table of contents for i, (title, page_num) in enumerate(zip(titles, page_numbers)): link_annotation = PyPDF2.generic.DictionaryObject({ PyPDF2.generic.NameObject("/Type"): PyPDF2.generic.NameObject("/Annot"), PyPDF2.generic.NameObject("/Subtype"): PyPDF2.generic.NameObject("/Link"), PyPDF2.generic.NameObject("/Rect"): PyPDF2.generic.ArrayObject([ PyPDF2.generic.FloatObject(100), PyPDF2.generic.FloatObject(700 - (i + 1) * 20), PyPDF2.generic.FloatObject(200), PyPDF2.generic.FloatObject(710 - (i + 1) * 20), ]), PyPDF2.generic.NameObject("/Border"): PyPDF2.generic.ArrayObject([ PyPDF2.generic.FloatObject(0), PyPDF2.generic.FloatObject(0), PyPDF2.generic.FloatObject(0), ]), PyPDF2.generic.NameObject("/A"): PyPDF2.generic.DictionaryObject({ PyPDF2.generic.NameObject("/Type"): PyPDF2.generic.NameObject("/Action"), PyPDF2.generic.NameObject("/S"): PyPDF2.generic.NameObject("/GoTo"), PyPDF2.generic.NameObject("/D"): PyPDF2.generic.ArrayObject([ PyPDF2.generic.NameObject(f"/Page"), PyPDF2.generic.NameObject(f"/Fit"), PyPDF2.generic.FloatObject(page_num - 1), # page_num is 1-based, but PyPDF2 is 0-based ]), }), }) toc_page.get_object().append(link_annotation) # Write the modified PDF to a file with open('output_pdf.pdf', 'wb') as f: output_pdf.write(f)if name == 'main': create_pdf_with_table_of_contents()
Error : page = PyPDF2.pdf.PageObject.createBlankPage(width=612, height=792) # Standard letter size in points (8.5 x 11 inches) ^^^^^^^^^^ AttributeError: module 'PyPDF2' has no attribute 'pdf'
- Assistant
- User
PyPDF2.errors.DeprecationError: PdfFileWriter is deprecated and was removed in PyPDF2 3.0.0. Use PdfWriter instead.
- Assistant