Create Bookmarks in PDF using Python

This topic explains how to create bookmarks in PDF using Python. It has all the details to set the environment, a list of steps, and a sample code to insert bookmark in PDF using Python. You will learn to create a bookmark for a single page or add child bookmarks to a main bookmark.

Steps to Bookmark a PDF using Python

  1. Set the environment to use Aspose.PDF for Python via .NET for creating a bookmark
  2. Load the source PDF file into the Document object for inserting a bookmark
  3. Create a new bookmark instance by setting the title
  4. Set the bookmark formatting
  5. Set the destination page using the GoToAction() method
  6. Use the append() method in the outline collection to add a bookmark
  7. Save the output PDF file with a new bookmark

These steps describe how to bookmark PDF document using Python. Load the source PDF, create a bookmark, set its parameters, and define the action for a particular page when this bookmark is clicked. Finally, call the append() method in the outlines collection to add the newly created bookmark and save the output.

Code to Add a Bookmark in PDF using Python

import aspose.pdf as pdf
# Load License
license = pdf.License()
license.set_license("License.lic")
# Load the PDF file
pdf_document = pdf.Document("bookmark.pdf")
# Initialize a new bookmark instance
bookmark = pdf.OutlineItemCollection(pdf_document.outlines)
bookmark.title = "Sample Bookmark"
bookmark.italic = True
bookmark.bold = True
# Specify the destination page for the bookmark
bookmark.action = pdf.annotations.GoToAction(pdf_document.pages[1])
# Insert the bookmark into the outline collection of the document
pdf_document.outlines.append(bookmark)
# Save the modified PDF to the specified file
pdf_document.save("target_pdf.pdf")
print("Done")

This code demonstrates how to add bookmarks to PDF using Python. You may repeat the bookmark creation process as many times as the number of bookmarks you want to add to the PDF. If you want to add a bookmark as a child to a bookmark, then append the child bookmark in the main bookmark and append the main bookmark to the document outlines collection.

This article has taught us to add the bookmark to a PDF. For drawing lines in a PDF, refer to the article on Draw lines on PDF using Python.

 English