append page to existing pdf file using python (and matplotlib?)
Question: I would like to append pages to an existing pdf file.

Currently, I am using matplotlib pdfpages. however, once the file is closed,
saving another figure into it overwrites the existing file rather than
appending.

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

I know appending is possible via multiple calls to pdf.savefig() before
calling pdf.close() but I would like to append to pdf that has already been
closed.

Alternatives to matplotlib would be appreciated also.


Answer: You may want to use [pyPdf](https://github.com/mstamy2/PyPDF2/) for this.

    
    
    # 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](http://www.blog.pythonlibrary.org/2010/05/15/manipulating-pdfs-with-
python-and-pypdf/)

Thereby you detach the plotting from the pdf-merging.

