将图和文本保存为PDF

时间:2018-07-13 01:12:23

标签: python pdf matplotlib reportlab

我正在使用pyplot生成几个图,我想将它们另存为PDF以及一些其他文本信息。当前,我将图存储为PDF,使用reportlab将文本信息存储为单独的PDF,然后使用PyPDF2合并两个pdf。理想情况下,我将能够一次将图和文本保存在一个PDF中。有可能吗?

from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter


fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
matches1.plot(x='time', y='qty', legend=False, ax=ax1)
matches2.plot(x='time', y='size', legend=False, ax=ax2)
plt.tight_layout()
fig = plt.gcf()
fig.savefig('plot.pdf')

packet = io.BytesIO()
can = canvas.Canvas(packet, pagesize=letter)
y = 400
can.drawString(60, y, "Total 1: ")
can.drawString(60, y-15, "Total 2: ")
can.drawString(60, y-30, "Total 3: ")
can.drawString(60, y-45, "Total 4: ")
can.save()

packet.seek(0)
new_pdf = PdfFileReader(packet)
page = new_pdf.getPage(0)

output = PdfFileWriter()
output.addPage(page)
outputStream = open("text.pdf", "wb")
output.write(outputStream)
outputStream.close()

file1 = PdfFileReader(open("text.pdf", "rb"))
file2 = PdfFileReader(open("plot.pdf", "rb"))

page = file1.getPage(0)
page.mergePage(file2.getPage(0))

output = PdfFileWriter()
output.addPage(page)
outputStream = open("output.pdf", "wb")
output.write(outputStream)
outputStream.close()

0 个答案:

没有答案