我尝试使用 Python 和 PyPDF2 包来阅读 PDF 文档。目标是读取pdf中的所有书签,并构建一个以书签页码为键、书签标题为值的字典。
互联网上没有太多关于如何实现它的支持,除了this文章。其中发布的代码不起作用,我不是 python 专家来纠正它。 PyPDF2 的阅读器对象有一个名为outlines它为您提供了所有书签对象的列表,但没有书签的页码,并且遍历该列表并不困难,因为书签之间没有父/子关系。
我在下面分享我的代码来阅读 pdf 文档并检查outlines财产。
import PyPDF2
reader = PyPDF2.PdfFileReader('SomeDocument.pdf')
print(reader.numPages)
print(reader.outlines[1][1])
通过使列表彼此嵌套来保留父/子关系。此示例代码将以缩进的目录形式递归显示书签:
import PyPDF2
def show_tree(bookmark_list, indent=0):
for item in bookmark_list:
if isinstance(item, list):
# recursive call with increased indentation
show_tree(item, indent + 4)
else:
print(" " * indent + item.title)
reader = PyPDF2.PdfFileReader("[your filename]")
show_tree(reader.getOutlines())
我不知道如何检索页码。我尝试了一些文件,并且page
的属性Destination
对象始终是一个实例IndirectObject
,其中似乎不包含任何有关页码的信息。
UPDATE:
有一个获取目标页码从中获取页码的方法Destination
对象。修改代码以创建您想要的字典:
import PyPDF2
def bookmark_dict(bookmark_list):
result = {}
for item in bookmark_list:
if isinstance(item, list):
# recursive call
result.update(bookmark_dict(item))
else:
result[reader.getDestinationPageNumber(item)] = item.title
return result
reader = PyPDF2.PdfFileReader("[your filename]")
print(bookmark_dict(reader.getOutlines()))
但是,请注意,如果同一页面上有多个书签(字典键必须是唯一的),您将覆盖并丢失一些值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)