2016-06-30 96 views
5

我想將頁面附加到現有的pdf文件。使用python(和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.savefig()調用pdf.close()之前,但我想追加到已經關閉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() 
相關問題