繁体   English   中英

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

[英]insert new page between existing pages in pdf using matplotlib in python

是否可以将新页面插入多页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()

现在,我想绘制其他图形并将新图形另存为pdf第1页。

您可以使用模块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)

也许有一种更聪明的方法可以做到这一点,但是我希望这可以帮助我们开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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