【问题标题】:How to delete pages from pdf file using Python?如何使用 Python 从 pdf 文件中删除页面?
【发布时间】:2017-01-27 04:44:57
【问题描述】:

我有一些超过 500 页的 .pdf 文件,但我只需要每个文件中的几页。有必要保留文档的标题页。我确切地知道程序应该删除的页数。我如何使用安装在 MS Visual Studio 上的 Python 2.7 环境来做到这一点?

【问题讨论】:

    标签: python pdf


    【解决方案1】:

    使用 pyPDF2:

    https://github.com/mstamy2/PyPDF2

    文档位于:

    https://pythonhosted.org/PyPDF2/

    看起来很直观。

    【讨论】:

      【解决方案2】:

      尝试使用PyPDF2。

      不要删除页面,而是创建一个新文档并添加您不想删除的所有页面。

      一些示例代码(最初改编自已死的 BinPress,存档here)。

      from PyPDF2 import PdfFileWriter, PdfFileReader
      pages_to_keep = [1, 2, 10] # page numbering starts from 0
      infile = PdfFileReader('source.pdf', 'rb')
      output = PdfFileWriter()
      
      for i in pages_to_keep:
          p = infile.getPage(i)
          output.addPage(p)
      
      with open('newfile.pdf', 'wb') as f:
          output.write(f)
      

      或

      from PyPDF2 import PdfFileWriter, PdfFileReader
      pages_to_delete = [3, 4, 5] # page numbering starts from 0
      infile = PdfFileReader('source.pdf', 'rb')
      output = PdfFileWriter()
      
      for i in range(infile.getNumPages()):
          if i not in pages_to_delete:
              p = infile.getPage(i)
              output.addPage(p)
      
      with open('newfile.pdf', 'wb') as f:
          output.write(f)
      

      【讨论】:

      • 或者只是for i in pages_to_keep: ...?
      • @Dennis:感谢您的关注!更新了答案、链接并添加了另一句解释。
      • @MaximilianPeters 我试过这个,对于 500 页的书,输出 pdf 文件大小比输入文件大小略大 0.3MB。文件大小增加的原因可能是什么,我只是好奇。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2011-11-10
      • 2017-12-21
      • 2018-09-07
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      相关资源
      最近更新 更多