繁体   English   中英

使用python(和matplotlib?)将页面附加到现有的pdf文件

[英]append page to existing pdf file using python (and matplotlib?)

我想将页面附加到现有的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.close()之前可以通过多次调用pdf.savefig()进行追加,但是我想附加到已经关闭的pdf。

matplotlib的替代品也将受到赞赏。

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

我搜索了一会儿,但是在程序的其他地方重新打开后找不到添加到同一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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM