Last modified: Jan 11, 2025 By Alexander Williams

Python PdfWriter.add_bookmark: Add Bookmarks to PDFs

Adding bookmarks to PDFs can make navigation easier. Python's PdfWriter.add_bookmark method helps you do this. This guide explains how to use it.

What is PdfWriter.add_bookmark?

The PdfWriter.add_bookmark method adds a bookmark to a PDF. It takes two main arguments: the bookmark title and the page number. This is useful for creating structured PDFs.

How to Use PdfWriter.add_bookmark

To use PdfWriter.add_bookmark, you need the PyPDF2 library. First, install it using pip. Then, import the library and create a PDF writer object.


# Install PyPDF2
# pip install PyPDF2

from PyPDF2 import PdfWriter, PdfReader

# Create a PDF writer object
writer = PdfWriter()

# Add pages to the writer
reader = PdfReader("example.pdf")
for page in reader.pages:
    writer.add_page(page)

# Add a bookmark
writer.add_bookmark("Chapter 1", 0)

# Save the new PDF
with open("bookmarked.pdf", "wb") as output_pdf:
    writer.write(output_pdf)

In this example, a bookmark titled "Chapter 1" is added to the first page of the PDF. The new PDF is saved as "bookmarked.pdf".

Adding Multiple Bookmarks

You can add multiple bookmarks to a PDF. Just call add_bookmark multiple times with different titles and page numbers.


# Add multiple bookmarks
writer.add_bookmark("Chapter 1", 0)
writer.add_bookmark("Chapter 2", 1)
writer.add_bookmark("Chapter 3", 2)

# Save the new PDF
with open("multi_bookmarked.pdf", "wb") as output_pdf:
    writer.write(output_pdf)

This code adds three bookmarks to the PDF. Each bookmark points to a different page.

Nested Bookmarks

You can also create nested bookmarks. This is useful for creating a hierarchical structure. Use the parent parameter to specify the parent bookmark.


# Add nested bookmarks
parent = writer.add_bookmark("Part 1", 0)
writer.add_bookmark("Chapter 1", 0, parent)
writer.add_bookmark("Chapter 2", 1, parent)

# Save the new PDF
with open("nested_bookmarked.pdf", "wb") as output_pdf:
    writer.write(output_pdf)

In this example, "Chapter 1" and "Chapter 2" are nested under "Part 1". This creates a more organized PDF.

Conclusion

Using PdfWriter.add_bookmark is a simple way to add bookmarks to PDFs. It helps in creating structured and navigable documents. Try it out in your next project!

For more on working with PDFs in Python, check out our guides on extracting text from PDFs and extracting PDF metadata.