我一直在尝试使用相同的前景将页面与 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句