I create an application, that merges multiple pdfs with a bookmark. If the origin pdfs already have bookmarks, I want to keep them and just add a bookmark at the beginning of the pdf. I use the following code: The title
and the path
in the code come from user input.
from PyPDF2 import PdfFileReader, PdfFileMerger
from PyPDF2.utils import PdfReadError
merger = PdfFileMerger()
pages_total = 0
for path, title in zip(paths, titles):
merger.append(path, import_bookmarks=True)
with open(path, "rb") as file:
pdf = PdfFileReader(file, "rb")
pages_one = pdf.getNumPages()
pages_total += pages_one
merger.addBookmark(f"{title}", pages_total - pages_one, parent=None)
save_path = input() + ".pdf"
merger.write(save_path)
merger.close()
The new pdf has all bookmarks, that points to the right pages. However, that bookmark for the entire pdf appears after the pdfs that already existed. How can I change the order in which the bookmarks are displayed?
The picture below hopefully clarifies the problem. The last bookmark was added and should be the first in the list.