使用Python(和Matplotlib?)将页面添加到现有的PDF文件中

10

我想将页面添加到现有的PDF文件中。

目前,我正在使用Matplotlib的pdfpages。但是,一旦文件关闭,将另一个图形保存到其中会覆盖现有文件,而不是追加到文件末尾。

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.savefig()然后再调用pdf.close()来实现追加,但是我想追加到已经关闭的pdf文件中。

同时也希望得到一些类似于matplotlib的替代方案。

2个回答

6
您可能想要使用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合并中分离出来。


1
@Bella 我更新了答案,使其与Python3兼容。 - ImportanceOfBeingErnest
如果我需要合并多个具有多页的PDF文件,怎么办? - Bella
我认为从答案中应该很清楚了吧?你打开它们并将它们所有的页面追加到输出中。 - ImportanceOfBeingErnest

2

我搜索了一段时间,但无法找到在程序的其他位置重新打开同一pdf文件后附加内容的方法。最终我使用了字典,这样我可以为我感兴趣的每个pdf文件存储数字,并在最后将它们写入pdf文件中。以下是一个示例:

dd = defaultdict(list)  #create a default dictionary
plot1 = df1.plot(kind='barh',stacked='True') #create a plot
dd[var].append(plot1.figure) #add figure to dictionary

#elsewhere in the program
plot2 = df2.plot(kind='barh',stacked='True') #another plot
dd[var].append(plot2.figure) #add figure to dictionary

#at the end print the figures to various reports
for var in dd.keys():
    pdf = PdfPages(var+.'pdf') #for each dictionary create a new pdf doc
    for figure in dd[k]:
        pdf.savefig(figure)   #write the figures for that dictionary
    pdf.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接