首页 > 解决方案 > Python - 如何将两个 pdf 页面合并为一个页面

问题描述

我正在使用 matplotlib 生成一系列图。每个图都针对不同的位置,因此图中的数据会发生变化。

我还有一个 pdf 模板,我想用它来粘贴其中的图。这个模板比我想在 matplotlib 中复制的要复杂。

我已将透明度设置为 True,因此我希望它能够很好地合并而不会覆盖模板的某些部分。

我尝试的是首先将 matplotlib 图导出为 pdf,然后使用 PyPDF2 将两个 pdf 合并在一起,但这似乎不起作用,因为我只是以两个单独的页面结束,这 duh ......但我我不知道从这里去哪里。

plt.savefig("testhole.pdf", transparent=True)
#Merge pdf's
path = r'C:\Users\xxx\PycharmProjects\xxx'
template_path = path + r'\Template.pdf'
testhole_file = path + r'\testhole.pdf'
test_hole_path = path + r'\\' + location + r'.pdf'
pdf_template = PdfFileReader(template_path)
pdf_testhole = PdfFileReader(testhole_file)
pdf_merger = PdfFileMerger()
pdf_merger.append(pdf_template)
pdf_merger.append(pdf_testhole)
with open(test_hole_path, 'wb') as fileobj:
    pdf_merger.write(fileobj)

标签: pythonpdf

解决方案


因为 append 需要fileobj通过 a 我认为你必须使用:

pdf_template = PdfFileReader(open(template_path, 'rb'))
pdf_testhole = PdfFileReader(open(testhole_file, 'rb'))

请让我知道这是否解决了您的问题


推荐阅读