使用 PyPDF2 合并多个 pdf 文档中的页面

Merging pages in multiple pdf documents with PyPDF2

我一直在尝试使用相同的前景将 PyPDF2 与 PyPDF2 合并到具有以下循环的多个文档中的多个页面。

for item in file_list: # loops through 16 pdf files

print("Processing " + item)

if item.endswith(".pdf"):

    output_to_file = "/Users/" + getuser() + "/Target/" + item

    background = PdfFileReader(open(source_files + item, "rb"))
    page_count = background.getNumPages()

    for n in range(page_count):

        x, y, w, h = background.getPage(n).mediaBox  # get size of mediaBox
        if w > h:
            foreground = PdfFileReader(open("b_landscape.pdf", "rb"))
        else:
            foreground = PdfFileReader(open("b_portrait.pdf", "rb"))

            input_file = background.getPage(n)
            input_file.mergePage(foreground.getPage(0))
            output.addPage(input_file)

    with open(output_to_file, "wb") as outputStream:
        output.write(outputStream)

结果是一系列大小不断增加的 pdf 文件,即第一个文件约为 6MB,在第 16 次循环后生成的文件约为 70MB。似乎正在发生的是前景图像被带入下一个循环。 我尝试使用

重新初始化 PageObject (input_file)
input_file = None

无济于事。如果有人有建议,将不胜感激。

关于您的代码,我认为除非我误解了您在做什么,否则 input_file 内容应该与 if 和 else 处于同一级别。我不认为这是你问的问题,但这是我首先看到的。

for item in file_list: # loops through 16 pdf files

print("Processing " + item)

if item.endswith(".pdf"):

    output_to_file = "/Users/" + getuser() + "/Target/" + item

    background = PdfFileReader(open(source_files + item, "rb"))
    page_count = background.getNumPages()

    for n in range(page_count):

        x, y, w, h = background.getPage(n).mediaBox  # get size of mediaBox
        if w > h:
            foreground = PdfFileReader(open("b_landscape.pdf", "rb"))
        else:
            foreground = PdfFileReader(open("b_portrait.pdf", "rb"))

        input_file = background.getPage(n)
        input_file.mergePage(foreground.getPage(0))
        output.addPage(input_file)

    with open(output_to_file, "wb") as outputStream:
        output.write(outputStream)