问题描述
我想将页面附加到现有的pdf文件中.
I would like to append pages to an existing pdf file.
当前,我正在使用matplotlib pdfpages.但是,一旦关闭文件,将另一个图形保存到其中将覆盖现有文件,而不是附加文件.
Currently, I am using matplotlib pdfpages. however, once the file is closed, saving another figure into it overwrites the existing file rather than appending.
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
class plotClass(object):
def __init__(self):
self.PdfFile='c:/test.pdf'
self.foo1()
self.foo2()
def foo1(self):
plt.bar(1,1)
pdf = PdfPages(self.PdfFile)
pdf.savefig()
pdf.close()
def foo2(self):
plt.bar(1,2)
pdf = PdfPages(self.PdfFile)
pdf.savefig()
pdf.close()
test=plotClass()
我知道可以在调用pdf.close()之前通过多次调用pdf.savefig()进行追加,但我想将其追加到已经关闭的pdf中.
I know appending is possible via multiple calls to pdf.savefig() before calling pdf.close() but I would like to append to pdf that has already been closed.
matplotlib的替代方案也将受到赞赏.
Alternatives to matplotlib would be appreciated also.
推荐答案
您可能要使用 pyPdf 一个>为此.
# Merge two PDFs
from PyPDF2 import PdfFileReader, PdfFileWriter
output = PdfFileWriter()
pdfOne = PdfFileReader(open("path/to/pdf1.pdf", "rb"))
pdfTwo = PdfFileReader(open("path/to/pdf2.pdf", "rb"))
output.addPage(pdfOne.getPage(0))
output.addPage(pdfTwo.getPage(0))
outputStream = open(r"output.pdf", "wb")
output.write(outputStream)
outputStream.close()
因此,您可以将绘图从pdf合并中分离出来.
Thereby you detach the plotting from the pdf-merging.
这篇关于使用python(和matplotlib?)将页面附加到现有的pdf文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!