pyPdf用于IndirectObject提取

发布于 2021-01-29 17:46:40

按照此示例,我可以将所有元素列出到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下)?

关注者
0
被浏览
36
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    您可以尝试单独打印或戳在它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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看