Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyPDF2 compression

Tags:

python

pdf

pypdf

I am struggling to compress my merged pdf's using the PyPDF2 module. this is my attempt based on 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'))

The error I receive is

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

I have also tried to compressing the pdf after the merging is complete. I am basing my failed compression on what file size I got after using PDFSAM with compression. Any thoughts? Thanks.

like image 699
nagordon Avatar asked Jun 17 '26 17:06

nagordon


2 Answers

PyPDF2 doesn't have a reliable compression method. That said, there's a compress_content_streams() method with the following description:

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.

Again, this won't make any difference in most cases but you can try this code:

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)
like image 157
xilopaint Avatar answered Jun 19 '26 05:06

xilopaint


pypdf offers several ways to reduce the file size (official docs)

compress_content_streams is one that only has the disadvantage that it might take long (depends on the PDF; think of it as ZIP-for-PDF):

from pypdf import PdfWriter

writer = PdfWriter(clone_from="example.pdf")

for page in writer.pages:
    page.compress_content_streams()  # This is CPU intensive!

with open("out.pdf", "wb") as f:
    writer.write(f)
like image 20
Martin Thoma Avatar answered Jun 19 '26 06:06

Martin Thoma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!