在python中使用matplotlib在pdf中的现有页面之间插入新页面

jla*_*sch 2 python pdf matplotlib

是否可以将新页面插入多页 pdf 文件的任意位置?

在这个虚拟示例中,我正在创建一些 pdf 页面:

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()
Run Code Online (Sandbox Code Playgroud)

现在我想绘制其他内容并将新图保存为 pdf 的第 1 页。

tot*_*i08 5

您可以使用模块PyPDF2。它使您可以合并或操作 pdf 文件。我尝试了一个简单的例子,创建另一个只有一页的 pdf 文件,并在第一个文件的中间添加这个页面。然后我将所有内容写入新的输出文件:

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)
Run Code Online (Sandbox Code Playgroud)

也许有更聪明的方法来做到这一点,但我希望这有助于开始。