简体   繁体   中英

Page number of added bookmarks with PyPDF2

I have added pdf files using PdfFileMerger from PyPDF2 and added a bookmark at the beginning of each pdf file using PdfFileMerger.addbookmark . When I open the new file with PdfFileReader and extract the pages, where the bookmarks wer placed, I get for the page number -1 .

I use the following code for merging:

merger = PdfFileMerger
for path in paths:
    merger.append(path, import_bookmarks=False)
    merger.addBookmark(f"{title}", page)
merger.write(save_path)
merger.close()

For reading the file I use:

pdf = PdfFileReader(file, "rb")
for i in pdf.getOutlines():
    pdf.getDestinationPageNumber(i)

Why is the page number -1 for the new bookmarks?

You are getting the -1 value because the method getDestinationPageNumber is not finding the page associated with the Destination object, see the documentation . In addition, outline iteration might be broken in PyPDF2, as suggested by this SO answer . You can achieve what you want with this code:

pdf = PdfFileReader(file, "rb")
for i in pdf.getOutlines():
    print(i.page)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM