有没有办法从pdf文档中提取图像(使用PyPDF2库)?也可以将一些图像替换为另一个图像(例如用PIL生成或从文件加载)?
我能够从pdf对象树中获取EncodedStreamObject并获得编码流(通过调用getData()方法),但看起来它只是原始内容,没有任何图像标题和其他元信息.
>>> import PyPDF2
>>> # sample.pdf contains png images
>>> reader = PyPDF2.PdfFileReader(open('sample.pdf', 'rb'))
>>> reader.resolvedObjects[0][9]
{'/BitsPerComponent': 8,
'/ColorSpace': ['/ICCBased', IndirectObject(20, 0)],
'/Filter': '/FlateDecode',
'/Height': 30,
'/Subtype': '/Image',
'/Type': '/XObject',
'/Width': 100}
>>>
>>> reader.resolvedObjects[0][9].__class__
PyPDF2.generic.EncodedStreamObject
>>>
>>> s = reader.resolvedObjects[0][9].getData()
>>> len(s), s[:10]
(9000, '\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc')
Run Code Online (Sandbox Code Playgroud)
我已经仔细研究过PyPDF2,ReportLab和PDFMiner解决方案,但没有找到类似我正在寻找的东西.
任何代码示例和链接都将非常有用.
我正在使用 python ReportLab canvas 生成带有水印的覆盖文档,以将其合并到源 pdf 文档中(使用PyPDF2)。最近,我遇到了包含旋转页面的文档的问题(pdf 中的页面对象存在 /Rotate 键)。该文档在设备和打印机上看起来没问题。但结果(合并)文档包含针对源文档旋转的水印。
所以源页面的 pdf 结构如下:
6 0 obj
<</Length 45>>
stream
q
1 0 0 1 2 4 cm
799 0 0 603 0 0 cm
/x5 Do
Q
endstream
endobj
7 0 obj
<</Type/Page/Parent 1 0 R
/Resources << /XObject << /x5 5 0 R >> >>
/MediaBox [0 0 792 612]
/Rotate 270/Contents 6 0 R
>>
endobj
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,页面旋转了 270 度。
我使用类似的脚本来生成和合并水印和源页面:
6 0 obj
<</Length 45>>
stream …Run Code Online (Sandbox Code Playgroud)