2016-06-30 53 views
5

Vorrei aggiungere le pagine a un file pdf esistente.aggiungi la pagina al file pdf esistente usando python (e matplotlib?)

Attualmente sto utilizzando le pagine pdf di matplotlib. tuttavia, una volta chiuso il file, il salvataggio di un'altra figura sovrascrive il file esistente anziché aggiungerlo.

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() 

so apposizione è possibile tramite chiamate multiple a pdf.savefig() prima di chiamare pdf.close(), ma vorrei aggiungere a pdf che è già stato chiuso.

Anche le alternative a matplotlib sarebbero apprezzate.

risposta

1

Si consiglia di utilizzare pyPdf per questo.

# 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

In tal modo si stacca il tracciato dal pdf-fusione.

1

Ho cercato in giro per un po 'ma non sono riuscito a trovare un modo per aggiungere lo stesso file pdf dopo averlo riaperto altrove nel programma. Ho finito per usare i dizionari, in questo modo posso memorizzare le figure nel dizionario per ogni pdf che mi interessa creare e scriverle in pdf alla fine. Ecco un esempio:

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() 
Problemi correlati