jlarsch
jlarsch

Reputation: 2307

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.

Upvotes: 2

Views: 2789

Answers (1)

toti08
toti08

Reputation: 2454

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.

Upvotes: 6

Related Questions