2016-06-30 42 views
5

私は既存のpdfファイルにページを追加したいと思います。python(とmatplotlib?)を使用して既存のpdfファイルにページを追加

現在、私はmatplotlib pdfpagesを使用しています。ただし、ファイルが閉じられると、別のFigureを保存すると、追加するのではなく既存のファイルが上書きされます。

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に代わるものもあります。

答えて

1

これにはpyPdfを使用します。

# Merge two PDFs 
from pyPdf import PdfFileReader, PdfFileWriter 

output = PdfFileWriter() 
pdfOne = PdfFileReader(file("some\path\to\a\PDf", "rb")) 
pdfTwo = PdfFileReader(file("some\other\path\to\a\PDf", "rb")) 

output.addPage(pdfOne.getPage(0)) 
output.addPage(pdfTwo.getPage(0)) 

outputStream = file(r"output.pdf", "wb") 
output.write(outputStream) 
outputStream.close() 

example taken from here

これにより、あなたは、PDF-マージからプロットを切り離します。

1

私はしばらく検索しましたが、プログラムの別の場所に再度開いた後、同じ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() 
関連する問題