2

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it basically produces the desired result. I was hoping I wouldn't have to re-assemble the file like this but it's a start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.