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

时间:2017-04-29 12:02:46

标签: python-3.x pdf pypdf2

我一直在尝试使用相同的前景将mergePage与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

无济于事。如果有人有任何建议,我们将非常感激。

1 个答案:

答案 0 :(得分:0)

关于你的代码,我认为除非我误解你正在做什么,否则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)
相关问题