使用 PyPDF2 向 PDF 添加书签

Add a bookmark to a PDF with PyPDF2

我正在尝试使用 PyPDF2 向 PDF 添加书签。我运行以下没有问题。但是永远不会创建书签。关于我做错了什么的任何想法。 PDF 有 2 页长。

from PyPDF2 import PdfFileReader, PdfFileWriter

reader = PdfFileReader("test.pdf")  # open input
writer = PdfFileWriter()  # open output
writer.addPage(reader.getPage(0))  # insert page
writer.addBookmark("Hello, World Bookmark", 0, parent=None)  # add bookmark

我 运行 您的代码(在其下方添加文本以写出 pdf)并发现书签实际上已创建。

from PyPDF2 import PdfFileReader, PdfFileWriter

writer = PdfFileWriter()  # open output
reader = PdfFileReader("test.pdf")  # open input
writer.addPage(reader.getPage(0))  # insert page
writer.addBookmark("Hello, World Bookmark", 0, parent=None)  # add bookmark
with open("result.pdf", "wb") as fp:  # creating result pdf JCT
    writer.write(fp)  # writing to result pdf JCT

检查结果中的书签面板。拥有书签不会自动导致 PDF 打开书签面板。

要使用 PyPDF2 打开书签面板,请添加一行:

writer = PdfFileWriter()  # open output
reader = PdfFileReader("test.pdf")  # open input
writer.addPage(reader.getPage(0))  # insert page
writer.addBookmark("Hello, World Bookmark", 0, parent=None)  # add bookmark
writer.setPageMode("/UseOutlines")  # This is what tells the PDF to open to bookmarks
with open("result.pdf", "wb") as fp:  # creating result pdf JCT
    writer.write(fp)  # writing to result pdf JCT

感谢 James 的代码。但它只输出一页pdf文件,并没有显示如何添加多个书签。这是他的代码的修订版本。

from PyPDF2 import PdfFileReader, PdfFileWriter

reader = PdfFileReader("test.pdf")  # open input
writer = PdfFileWriter()  # open output

n = reader.getNumPages()

for i in range(n):
    writer.addPage(reader.getPage(i))  # insert page


# add a bookmark on the first page
writer.addBookmark("Hello, World Bookmark", 0, parent=None)

# add a bookmark on the sixth page
par = writer.addBookmark("Second Bookmark", 5, parent=None)

# add a child bookmark on the eighth page
writer.addBookmark("Third Bookmark", 7, parent=par)

with open("result.pdf", "wb") as fp:  # creating result pdf JCT
    writer.write(fp)  # writing to result pdf JCT