【问题标题】:Using PyPDF2 to merge files into multiple output files使用 PyPDF2 将文件合并为多个输出文件
【发布时间】:2015-05-01 05:08:37
【问题描述】:

这是导致问题的代码块。循环每次都会追加新文件,这不是我想要完成的。比如outputfile1就是input1.pdf,outputfile2就是input1.pdf + input2.pdf...

我正在尝试将文件 1x.pdf 与文件 1a.pdf + 1b.pdf + 1c.pdf 合并到输出 file1.pdf 中,然后循环并为 2、3 和 4 执行相同的操作。结束结果应该是 4 个单独的文件。我错过了什么?清如泥?提前感谢您的任何帮助。

i = 1

while i < 5:
    # files to be merged

    input1 = open(Path1+str(i)+"x.PDF", "rb")
    input2 = open(Path2+str(i)+"a.PDF", "rb")
    input3 = open(Path2+str(i)+"b.PDF", "rb")
    input4 = open(Path2+str(i)+"c.PDF", "rb")

    # output files
    output_file = open("/NewFile"+str(i)+".pdf", "wb")

    # add input1 document to output
    merger.append(fileobj = input1, pages = (0, 3, 2), import_bookmarks = False)

    # insert the pages of input2 into the output beginning after the second page
    merger.append(input2)

    # insert the pages of input3 into the output beginning after the second page
    merger.append(input3)

    # insert the pages of input4 into the output beginning after the second page
    merger.append(input4)

    # Write to an output PDF document
    merger.write(output_file)
    output_file.close()

    i += 1

【问题讨论】:

  • 您的问题不清楚,但我强烈建议您查看pdftk 以连接PDF 文件。见stackoverflow.com/a/2507825/145400
  • 是的,很难说清楚。简而言之,如果我手动更改迭代器变量,效果很好。如果我写一个循环,它不会。几乎就像离散地(每次)运行程序一样清除内存或其他东西。我将查看您引用的库。谢谢。

标签: python python-2.7 pdf pypdf


【解决方案1】:

复活一个超级老问题,但遇到了这个问题并想回答,希望能防止其他人将您的部分代码粘贴到上面并遇到同样的问题。

没有看到其余部分,我只是猜测,但您的循环不会创建新的merger,它只是不断地追加和追加,这就是您报告的问题。我希望如果您将合并初始化代码带入循环中(以便每次迭代都重新设置),您将获得所需的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多