Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may want to use pyPdf for this.

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

example taken from here

Thereby you detach the plotting from the pdf-merging.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...