I have a PDF file of around 7000 pages and 479 MB. I have create a python script using PyPDF4 to extract only specific pages if the pages contain specific words. The script works but the new PDF file, even though it has only 650 pages from the original 7000, now has more MB that the original file (498 MB to be exactly).
Is there any way to lower the filesize of the new PDF?
The script I used:
from PyPDF4 import PdfFileWriter, PdfFileReader
import os
import re
output = PdfFileWriter()
input = PdfFileReader(open('Binder.pdf', 'rb')) # open input
for i in range(0, input.getNumPages()):
content = ""
content += input.getPage(i).extractText() + "\n"
#Format 1
RS = re.search('FIGURE', content)
RS1 = #... Only one search given as example. I have more, but are irrelevant for the question.
#....
# Format 2
RS20 = re.search('FIG.', content)
RS21 = #... Only one search given as example. I have more, but are irrelevant for the question.
#....
if (all(v is not None for v in [RS, RS1, RS2, RS3, RS4, RS5, RS6, RS7, RS8, RS9]) or all(v is not None for v in [RS20, RS21, RS22, RS23, RS24, RS25, RS26, RS27, RS28, RS29, RS30, RS30])):
p = input.getPage(i)
output.addPage(p)
#Save pages to new PDF file
with open('ExtractedPages.pdf', 'wb') as f:
output.write(f)
After a lot of searching found some solutions. The only problem with the exported PDF file was that it was uncompressed. So I needed a solution to compress a PDF file:
PyPDF2 and/or PyPDF4 do not have an option to compress PDFs. PyPDF2 had the compressContentStreams() method, which doesn't work.
Found a few other solutions that claim to compress PDFs, but none worked for me (adding them here just in case they work for others): pylovepdf ; pdfsizeopt ; pdfc
The first solution that worked for me was Adobe Acrobat professional. It reduced the size from 498 MB to 2.99 MB.
[Best Solution] As an alternative, open source solution that works, I found coherentpdf. For Windows you can download the pre-built PDF squeezer tool. Then in cmd:
cpdfsqueeze.exe input.pdf output.pdf
This actually compressed the PDF even more than Adobe Acrobat. From 498 MB to 2.48 MB. Compressed to 0.5% from original. I think this is the best solution as it can be added to your Python Code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With