PyPDF4 - 导出的 PDF 文件太大

PyPDF4 - Exported PDF file size too big

我有一个大约 7000 页和 479 MB 的 PDF 文件。 如果页面包含特定单词,我已经使用 PyPDF4 创建了一个 python 脚本来仅提取特定页面。 该脚本有效,但新的 PDF 文件,即使它只有原始 7000 页的 650 页,现在的 MB 比原始文件多(准确地说是 498 MB)。

有什么方法可以降低新 PDF 的文件大小吗?

我使用的脚本:

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)

经过大量搜索找到了一些解决方案。 导出的 PDF 文件的唯一问题是它 uncompressed。所以我需要一个压缩 PDF 文件的解决方案:

  1. PyPDF2 and/or PyPDF4 没有压缩 PDF 的选项。 PyPDF2 有 compressContentStreams() method, which doesn't work.

  2. 找到了一些声称可以压缩 PDF 的其他解决方案,但 none 对我有用(将它们添加到此处以防它们对其他人有用): pylovepdf ; pdfsizeopt ; pdfc

  3. 对我有用的第一个解决方案是 Adob​​e Acrobat 专业版。它将大小从 498 MB 减少到 2.99 MB。

  4. [最佳解决方案] 作为替代的开源解决方案,我找到了 coherentpdf。 对于 Windows,您可以下载预构建的 PDF 压缩器工具。 然后在命令中:

    cpdfsqueeze.exe input.pdf output.pdf

这实际上压缩了 PDF,甚至比 Adob​​e Acrobat 压缩得更多。从 498 MB 到 2.48 MB。压缩到原来的 0.5%。我认为这是最好的解决方案,因为它可以添加到您的 Python 代码中。

  1. 编辑: 找到了另一个也有 GUI 的免费解决方案。 PDFsam。您可以在一个 PDF 文件上使用合并功能,并在高级设置中确保选中压缩输出。这从 498 压缩到 3.2 MB。

在Linux中,您可以使用ps2pdf工具压缩生成的pdf文件,该工具是ghostscript套件的一部分。 安装 ghostscript:

$ sudo apt-get install ghostscript

运行以下命令减小大pdf文件的大小

$ ps2pdf large.pdf compressed.pdf

当我尝试这个时,我没有发现任何质量损失。

如果您不介意丢失 PDF 中的任何链接,请尝试在保存文件之前调用 PdfFileWriter.removeLinks() 函数。我遇到了同样的问题,但在我保存之前调用此函数使我的文件大小从 44.7MB 减小到仅 1.09MB。