Skip to main content
 首页 » 编程设计

python之PyPDF2压缩

2024年11月01日10JeffreyZhao

我正在努力使用 PyPDF2 模块压缩合并后的 pdf。这是我基于 http://www.blog.pythonlibrary.org/2012/07/11/pypdf2-the-new-fork-of-pypdf/ 的尝试

import PyPDF2 
path = open('path/to/hello.pdf', 'rb') 
path2 = open('path/to/another.pdf', 'rb') 
merger = PyPDF2.PdfFileMerger() 
merger.append(fileobj=path2) 
merger.append(fileobj=path) 
pdf.filters.compress(merger) 
merger.write(open("test_out2.pdf", 'wb')) 

我收到的错误是

TypeError: must be string or read-only buffer, not file 

我还尝试在合并完成后压缩 pdf。我将失败的压缩基于使用 PDFSAM 进行压缩后得到的文件大小。 有什么想法吗?谢谢。

请您参考如下方法:

PyPDF2 没有可靠的压缩方法。也就是说,有一个 compress_content_streams()方法描述如下:

Compresses the size of this page by joining all content streams and applying a FlateDecode filter.

However, it is possible that this function will perform no action if content stream compression becomes "automatic" for some reason.

同样,这在大多数情况下不会有任何区别,但您可以尝试以下代码:

from PyPDF2 import PdfReader, PdfWriter 
 
 
writer = PdfWriter() 
 
for pdf in ["path/to/hello.pdf", "path/to/another.pdf"]: 
    reader = PdfReader(pdf) 
    for page in reader.pages: 
        page.compress_content_streams() 
        writer.add_page(page) 
 
with open("test_out2.pdf", "wb") as f: 
    writer.write(f)