是否可以使用Python合并单独的PDF文件?

假设是这样,我需要进一步扩展.我希望在目录中的文件夹中循环并重复这个过程.

我可能很走运,但是否可以排除每个PDF中包含的页面(我的报告生成总是创建一个额外的空白页面).

推荐答案

使用Pypdf或其后续版本PyPDF2:

作为PDF工具包构建的纯Python库.它能够:

  • 一页一页地拆分文档,
  • 一页一页地合并文档,

(还有更多)

下面是一个适用于这两个版本的示 routine 序.

#!/usr/bin/env python
import sys
try:
    from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError:
    from pyPdf import PdfFileReader, PdfFileWriter

def pdf_cat(input_files, output_stream):
    input_streams = []
    try:
        # First open all the files, then produce the output file, and
        # finally close the input files. This is necessary because
        # the data isn't read from the input files until the write
        # operation. Thanks to
        # https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
        for input_file in input_files:
            input_streams.append(open(input_file, 'rb'))
        writer = PdfFileWriter()
        for reader in map(PdfFileReader, input_streams):
            for n in range(reader.getNumPages()):
                writer.addPage(reader.getPage(n))
        writer.write(output_stream)
    finally:
        for f in input_streams:
            f.close()
        output_stream.close()

if __name__ == '__main__':
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    pdf_cat(sys.argv[1:], sys.stdout)

Python相关问答推荐

用ctype构建指针链

如何在WTForm中使用back_plumates参考brand_id?

code _tkinter. Tcl错误:窗口路径名称错误.!按钮4"

给定数据点,制定它们的关系

使用多个性能指标执行循环特征消除

ambda将时间戳与组内另一列的所有时间戳进行比较

在使用Guouti包的Python中运行MPP模型时内存不足

如何从FDaGrid实例中删除某些函数?

如何在BeautifulSoup中链接Find()方法并处理无?

三个给定的坐标可以是矩形的点吗

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

. str.替换pandas.series的方法未按预期工作

使用索引列表列表对列进行切片并获取行方向的向量长度

用Python解密Java加密文件

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

如何使用SentenceTransformers创建矢量嵌入?

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

基于Scipy插值法的三次样条系数