使用PyPDF2将文件合并为多个输出文件 [英] Using PyPDF2 to merge files into multiple output files

查看:206
本文介绍了使用PyPDF2将文件合并为多个输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是引起问题的代码块.循环每次都会追加新文件,这不是我要完成的工作.例如,outputfile1是input1.pdf,outputfile2是input1.pdf + input2.pdf ...

Here is the code block that is causing the issue. The loop will append the new file each time, which is not what I am trying to accomplish. For example, outputfile1 is input1.pdf, outputfile2 is input1.pdf + input2.pdf...

我正在尝试将文件1x.pdf与文件1a.pdf + 1b.pdf + 1c.pdf合并到输出file1.pdf中,然后遍历并针对2、3和4做同样的事情.结果应该是4个单独的文件.我想念什么?像泥一样清澈?在此先感谢您的协助.

I am trying to merge file 1x.pdf with files 1a.pdf + 1b.pdf + 1c.pdf into the output file1.pdf and then loop through and do the same thing for 2, 3, and 4. The end result should be 4 separate files. What am I missing? Clear as mud? Thanks in advance for any assistance.

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

推荐答案

复活一个非常老的问题,但遇到了这个问题,想回答这个问题,希望可以防止其他人将您的部分代码粘贴到上面并遇到相同的问题.

Resurrecting a super old question but ran into this and wanted to answer to hopefully prevent others from pasting your partial code above and running into the same problem.

我只剩下猜测的余地,但是您的循环并没有创建新的merger,它只是不断地追加,追加和追加,这就是您要报告的问题.我希望,如果将合并初始化代码带入循环(以便每次迭代都重新设置),那么您将找到所需的内容.

Without seeing the rest I'm only guessing, but your loop doesn't create a new merger, it just keeps appending and appending and appending, which is what you're reporting as the issue. I expect if you bring your merger initialization code into the loop (so that it gets re-setup each iteration) you'll have what you're looking for.

这篇关于使用PyPDF2将文件合并为多个输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆