使用python(和matplotlib?)将页面附加到现有的pdf文件中 [英] append page to existing pdf file using python (and matplotlib?)

查看:282
本文介绍了使用python(和matplotlib?)将页面附加到现有的pdf文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to append pages to an existing pdf file.

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

Currently, I am using matplotlib pdfpages. however, once the file is closed, saving another figure into it overwrites the existing file rather than appending.

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中.

I know appending is possible via multiple calls to pdf.savefig() before calling pdf.close() but I would like to append to pdf that has already been closed.

matplotlib的替代方案也将受到赞赏.

Alternatives to matplotlib would be appreciated also.

推荐答案

您可能要使用 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()

从此处获取的示例

因此,您可以将绘图从pdf合并中分离出来.

Thereby you detach the plotting from the pdf-merging.

这篇关于使用python(和matplotlib?)将页面附加到现有的pdf文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆