简体   繁体   中英

insert new page between existing pages in pdf using matplotlib in python

Is it possible to insert a new page into an arbitrary position of a multi page pdf file?

In this dummy example, I am creating some pdf pages:

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

with PdfPages('dummy.pdf') as pdf:
    for i in range(5):
        plt.plot(1,1)
        pdf.savefig()
        plt.close()

now I would like to plot something else and save the new plot as page 1 of the pdf.

You can use the module PyPDF2 . It gives you the possibility to merge or manipulate pdf files. I tried a simple example, creating another pdf file with 1 page only and adding this page in the middle of the first file. Then I write everything to a new output file:

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from PyPDF2 import PdfFileWriter, PdfFileReader


with PdfPages('dummy.pdf') as pdf:
    for i in range(5):
        plt.plot(1,1)
        pdf.savefig()
        plt.close()

#Create another pdf file
with PdfPages('dummy2.pdf') as pdf:
    plt.plot(range(10))
    pdf.savefig()
    plt.close()


infile = PdfFileReader('dummy.pdf', 'rb')
infile2 = PdfFileReader('dummy2.pdf', 'rb')
output = PdfFileWriter()

p2 = infile2.getPage(0)

for i in xrange(infile.getNumPages()):
    p = infile.getPage(i)
    output.addPage(p)
    if i == 3:
        output.addPage(p2)

with open('newfile.pdf', 'wb') as f:
   output.write(f)

Maybe there is a smarter way to do that, but I hope this helps to start with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM