使用PyPDF2添加书签 [英] Adding bookmarks using PyPDF2
问题描述
PyPDF2 的文档指出,可以将嵌套书签添加到PDF文件,并且该代码出现(阅读时)以支持此操作.
The documentation for PyPDF2 states that it's possible to add nested bookmarks to PDF files, and the code appears (upon reading) to support this.
将书签添加到根树很容易(请参见下面的代码),但是我无法弄清楚需要使用什么作为parent
参数来创建嵌套书签.我想创建一个类似这样的结构:
Adding a bookmark to the root tree is easy (see code below), but I can't figure out what I need to pass as the parent
argument to create a nested bookmark. I want to create a structure something like this:
Group A
Page 1
Page 2
Group A
Page 3
Page 4
这可能吗?
向树的根添加书签的示例代码:
Sample code to add a bookmark to the root of the tree:
#!/usr/bin/env python
from PyPDF2 import PdfFileWriter, PdfFileReader
output = PdfFileWriter() # open output
input = PdfFileReader(open('input.pdf', 'rb')) # open input
output.addPage(input.getPage(0)) # insert page
output.addBookmark('Hello, World', 0, parent=None) # add bookmark
PyPDF2 addBookmark函数: https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py#L517
PyPDF2 addBookmark function: https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py#L517
推荐答案
addBookmark
方法返回对其创建的书签的引用,该引用可用作另一个书签的父级.例如
The addBookmark
method returns a reference to the bookmark it created, which can be used as the parent to another bookmark. e.g.
#!/usr/bin/env python
from PyPDF2 import PdfFileWriter, PdfFileReader
output = PdfFileWriter()
input1 = PdfFileReader(open('introduction.pdf', 'rb'))
output.addPage(input1.getPage(0))
input2 = PdfFileReader(open('hello.pdf', 'rb'))
output.addPage(input2.getPage(0))
parent = output.addBookmark('Introduction', 0) # add parent bookmark
output.addBookmark('Hello, World', 0, parent) # add child bookmark
这篇关于使用PyPDF2添加书签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!