回答问题

按照这个例子,我可以将所有元素列出到一个 pdf 文件中

import pyPdf
pdf = pyPdf.PdfFileReader(open("pdffile.pdf"))
list(pdf.pages) # Process all the objects.
print pdf.resolvedObjects

现在,我需要从 pdf 文件中提取一个非标准对象。

我的对象是名为 MYOBJECT 的对象,它是一个字符串。

与我有关的python脚本打印的部分是:

{'/MYOBJECT': IndirectObject(584, 0)}

pdf文件是这样的:

558 0 obj
<</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 R/Resources
  <</ColorSpace <</CS0 563 0 R>>
    /ExtGState <</GS0 568 0 R>>
    /Font<</TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R>>
    /ProcSet[/PDF/Text/ImageC]
    /Properties<</MC0<</MYOBJECT 584 0 R>>/MC1<</SubKey 582 0 R>> >>
    /XObject<</Im0 578 0 R>>>>
  /Rotate 0/StructParents 0/Type/Page>>
endobj
...
...
...
584 0 obj
<</Length 8>>stream

1_22_4_1     --->>>>  this is the string I need to extract from the object

endstream
endobj

如何按照584值来引用我的字符串(当然是在 pyPdf 下)?

Answers

pdf.pages中的每个元素都是一个字典,所以假设它在第 1 页,pdf.pages[0]['/MYOBJECT']应该是你想要的元素。

您可以尝试单独打印或在 python 提示符中使用helpdir戳它,以了解有关如何获取所需字符串的更多信息

编辑:

在收到 pdf 的副本后,我在pdf.resolvedObjects[0][558]['/Resources']['/Properties']['/MC0']['/MYOBJECT']找到了该对象,并且可以通过 getData() 检索该值

下面的函数提供了一种更通用的方法来通过递归查找有问题的键来解决这个问题

import types
import pyPdf
pdf = pyPdf.PdfFileReader(open('file.pdf'))
pages = list(pdf.pages)

def findInDict(needle,haystack):
    for key in haystack.keys():
        try:
            value = haystack[key]
        except:
            continue
        if key == needle:
            return value
        if type(value) == types.DictType or isinstance(value,pyPdf.generic.DictionaryObject):  
            x = findInDict(needle,value)
            if x is not None:
                return x

answer = findInDict('/MYOBJECT',pdf.resolvedObjects).getData()
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐