【问题标题】:append page to existing pdf file using python (and matplotlib?)使用python(和matplotlib?)将页面附加到现有的pdf文件
【发布时间】:2016-11-02 06:40:09
【问题描述】:

我想将页面附加到现有的 pdf 文件中。

目前,我正在使用 matplotlib pdfpages。但是,一旦文件关闭,将另一个图形保存到其中会覆盖现有文件而不是追加。

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt



class plotClass(object):
    def __init__(self):
        self.PdfFile='c:/test.pdf'
        self.foo1()
        self.foo2()


    def foo1(self):
        plt.bar(1,1)
        pdf = PdfPages(self.PdfFile)
        pdf.savefig()
        pdf.close()

    def foo2(self):
        plt.bar(1,2)
        pdf = PdfPages(self.PdfFile)
        pdf.savefig()
        pdf.close()

test=plotClass()

我知道在调用 pdf.close() 之前可以通过多次调用 pdf.savefig() 来追加,但我想追加到已经关闭的 pdf。

matplotlib 的替代品也将不胜感激。

【问题讨论】:

    标签: python pdf matplotlib


    【解决方案1】:

    您可能希望为此使用pyPdf

    # Merge two PDFs
    from PyPDF2 import PdfFileReader, PdfFileWriter
    
    output = PdfFileWriter()
    pdfOne = PdfFileReader(open("path/to/pdf1.pdf", "rb"))
    pdfTwo = PdfFileReader(open("path/to/pdf2.pdf", "rb"))
    
    output.addPage(pdfOne.getPage(0))
    output.addPage(pdfTwo.getPage(0))
    
    outputStream = open(r"output.pdf", "wb")
    output.write(outputStream)
    outputStream.close()
    

    example taken from here

    从而您将绘图从 pdf 合并中分离出来。

    【讨论】:

    • @Bella 我将答案更新为兼容 python3。
    • 如果我需要附加 pdf 文件,每个文件有几页怎么办?
    • 我认为从答案中应该很清楚,对吧?您打开它们并将它们的所有页面附加到输出中。
    【解决方案2】:

    我搜索了一段时间,但在程序的其他地方重新打开后,找不到附加到同一个 pdf 文件的方法。我最终使用了字典,这样我就可以将每个我有兴趣创建的 pdf 的数字存储到字典中,并在最后将它们写入 pdf。这是一个例子:

    dd = defaultdict(list)  #create a default dictionary
    plot1 = df1.plot(kind='barh',stacked='True') #create a plot
    dd[var].append(plot1.figure) #add figure to dictionary
    
    #elsewhere in the program
    plot2 = df2.plot(kind='barh',stacked='True') #another plot
    dd[var].append(plot2.figure) #add figure to dictionary
    
    #at the end print the figures to various reports
    for var in dd.keys():
        pdf = PdfPages(var+.'pdf') #for each dictionary create a new pdf doc
        for figure in dd[k]:
            pdf.savefig(figure)   #write the figures for that dictionary
        pdf.close()
    

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 2022-10-04
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多