【问题标题】:Merging pages in multiple pdf documents with PyPDF2使用 PyPDF2 合并多个 pdf 文档中的页面
【发布时间】:2023-03-12 00:56:01
【问题描述】:

我一直在尝试将Page与 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 处于同一级别。我不认为这是您要问的问题,但这是我首先看到的。
  • 谢谢詹姆斯。我想你一针见血了!发布后,我确实注意到了缩进问题并更改了代码以包含 input_file.compressContentStreams() 并以不同方式处理外部循环,我得到了我正在寻找的结果。
  • 酷。我将发表我的评论作为答案。如果您愿意投票,我将不胜感激。

标签: python-3.x pdf pypdf2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2017-05-03
    • 2020-12-29
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    相关资源
    最近更新 更多