8
from typing import List
from PyPDF2 import PdfFileReader
from PyPDF2.generic import Destination


def get_outlines(pdf_filepath: str) -> List[Destination]:
    """Get the bookmarks of a PDF file."""
    with open(pdf_filepath, "rb") as fp:
        pdf_file_reader = PdfFileReader(fp)
        outlines = pdf_file_reader.getOutlines()
    return outlines


print(get_outlines("PDF-export-example.pdf"))

pyPdf.pdf.Destination有很多属性,但我找不到该书签的任何引用页码。如何获取书签的页码?


例如outlines[1].page.idnum,返回的数字大约是 PDF 文档中引用的页码的 3 倍,我假设它引用了一些小于页面的对象,因为.page.idnum在整个 PDF 文档大纲上运行返回的数字数组甚至与“真实”没有线性相关PDF 文档中的页码目标,大约是 3 倍


更新:这个问题与此相同:尽管我不明白作者在那里的自我回答中做了什么,但根据大纲拆分了一个 pdf 。对我来说似乎太复杂而无法使用

4

4 回答 4

10

正如@theta 指出的那样,“根据大纲拆分pdf ”具有提取页码所需的代码。如果您觉得这很复杂,我复制了将页面 id 映射到页码的部分代码,并使其成为一个函数。这是一个打印书签 o[0] 的页码的工作示例:

from PyPDF2 import PdfFileReader


def _setup_page_id_to_num(pdf, pages=None, _result=None, _num_pages=None):
    if _result is None:
        _result = {}
    if pages is None:
        _num_pages = []
        pages = pdf.trailer["/Root"].getObject()["/Pages"].getObject()
    t = pages["/Type"]
    if t == "/Pages":
        for page in pages["/Kids"]:
            _result[page.idnum] = len(_num_pages)
            _setup_page_id_to_num(pdf, page.getObject(), _result, _num_pages)
    elif t == "/Page":
        _num_pages.append(1)
    return _result
# main
f = open('document.pdf','rb')
p = PdfFileReader(f)
# map page ids to page numbers
pg_id_num_map = _setup_page_id_to_num(p)
o = p.getOutlines()
pg_num = pg_id_num_map[o[0].page.idnum] + 1
print(pg_num)

@theta 可能为时已晚,但可能对其他人有所帮助:) 顺便说一句,我在 stackoverflow 上的第一篇文章,如果我没有遵循通常的格式,请见谅

进一步扩展: 如果您想在页面上获取书签的确切位置,这将使您的工作更轻松:

from PyPDF2 import PdfFileReader
import PyPDF2 as pyPdf

def _setup_page_id_to_num(pdf, pages=None, _result=None, _num_pages=None):
    if _result is None:
        _result = {}
    if pages is None:
        _num_pages = []
        pages = pdf.trailer["/Root"].getObject()["/Pages"].getObject()
    t = pages["/Type"]
    if t == "/Pages":
        for page in pages["/Kids"]:
            _result[page.idnum] = len(_num_pages)
            _setup_page_id_to_num(pdf, page.getObject(), _result, _num_pages)
    elif t == "/Page":
        _num_pages.append(1)
    return _result
def outlines_pg_zoom_info(outlines, pg_id_num_map, result=None):
    if result is None:
        result = dict()
    if type(outlines) == list:
        for outline in outlines:
            result = outlines_pg_zoom_info(outline, pg_id_num_map, result)
    elif type(outlines) == pyPdf.pdf.Destination:
        title = outlines['/Title']
        result[title.split()[0]] = dict(title=outlines['/Title'], top=outlines['/Top'], \
        left=outlines['/Left'], page=(pg_id_num_map[outlines.page.idnum]+1))
    return result

# main
pdf_name = 'document.pdf'
f = open(pdf_name,'rb')
pdf = PdfFileReader(f)
# map page ids to page numbers
pg_id_num_map = _setup_page_id_to_num(pdf)
outlines = pdf.getOutlines()
bookmarks_info = outlines_pg_zoom_info(outlines, pg_id_num_map)
print(bookmarks_info)

注意:我的书签是节号(例如:1.1 简介),我将书签信息映射到节号。如果您的书签不同,请修改这部分代码:

    elif type(outlines) == pyPdf.pdf.Destination:
        title = outlines['/Title']
        result[title.split()[0]] = dict(title=outlines['/Title'], top=outlines['/Top'], \
        left=outlines['/Left'], page=(pg_id_num_map[outlines.page.idnum]+1))
于 2014-02-12T00:23:00.343 回答
5

使用 vjayky 和 ​​Giulio D 建议递归地管理书签

PyPDF2 >= v1.25

from PyPDF2 import PdfFileReader

def printBookmarksPageNumbers(pdf):
    def review_and_print_bookmarks(bookmarks, lvl=0):
        for b in bookmarks:
            if type(b) == list:
                review_and_print_bookmarks(b, lvl + 4)
                continue
            pg_num = pdf.getDestinationPageNumber(b) + 1 #page count starts from 0
            print("%s%s: Page %s" %(" "*lvl, b.title, pg_num))
    review_and_print_bookmarks(pdf.getOutlines())

with open('document.pdf', "rb") as f:
    pdf = PdfFileReader(f)
    printBookmarksPageNumbers(pdf)

PyPDF2 < v1.25

from PyPDF2 import PdfFileReader

def printBookmarksPageNumbers(pdf):
    # Map page ids to page numbers
    pg_id_to_num = {}
    for pg_num in range(0, pdf.getNumPages()):
        pg_id_to_num[pdf.getPage(pg_num).indirectRef.idnum] = pg_num

    def review_and_print_bookmarks(bookmarks, lvl=0):
        for b in bookmarks:
            if type(b) == list:
                review_and_print_bookmarks(b, lvl + 4)
                continue
            pg_num = pg_id_to_num[b.page.idnum] + 1 #page count starts from 0 
            print("%s%s: Page %s" %(" "*lvl, b.title, pg_num))
    review_and_print_bookmarks(pdf.getOutlines())

with open('document.pdf', "rb") as f:
    pdf = PdfFileReader(f)
    printBookmarksPageNumbers(pdf)
于 2020-09-06T20:41:17.047 回答
3

在 2019 年,对于那些对更快方式感兴趣的人,可以使用:

from PyPDF2 import PdfFileReader

def printPageNumberFrom(filename):
    with open(filename, "rb") as f:
       pdf = PdfFileReader(f)
       bookmarks = pdf.getOutlines()
       for b in bookmarks:
           print(pdf.getDestinationPageNumber(b) + 1) #page count starts from 0 
于 2019-09-03T12:52:44.653 回答
0

我不确定,但根据http://pybrary.net/pyPdf/pythondoc-pyPdf.pdf.html#pyPdf.pdf.Destination.page-attribute上 pyPdf.Destination 的文档,书签的页码只是目的地.page 。

于 2011-11-30T18:19:53.780 回答