【问题标题】:insert new page between existing pages in pdf using matplotlib in python在 python 中使用 matplotlib 在 pdf 中的现有页面之间插入新页面
【发布时间】:2016-03-08 05:19:20
【问题描述】:

是否可以在多页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 页。

【问题讨论】:

    标签: python pdf matplotlib


    【解决方案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)
    

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

    【讨论】:

    • 谢谢,它基本上产生了预期的结果。我希望我不必像这样重新组装文件,但这是一个开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多