我尝试使用 PyPDF2 和 Reportlab 向一个已经存在的 pdf 中的指定位置插入一个由 reportlab 生成的饼状图,但是我看的时候只看到使用 reportlab 的 canvas 向其中写入字符串,图片啥的,没看到写入一个 pie 对象,是要将这个 pie 对象转成图片然后再插入吗,我参考的是这个代码,先感谢各位大佬的教育
from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 100, "Hello world")
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()
1
lanceadd OP 我会了
``` import io from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.graphics import renderPDF from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.shapes import Drawing from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas packet = io.BytesIO() can = canvas.Canvas(packet, pagesize=A4) pie = Pie() pie.data = [20, 10, 5, 5, 5] pie.labels = ['a', 'b', 'c', 'd', 'e'] pie.sideLabels = True d = Drawing(100, 100) d.add(pie) renderPDF.draw(d, can, 20, 20) can.save() packet.seek(0) new_pdf = PdfFileReader(packet) existing_pdf = PdfFileReader(open('example_06.pdf', 'rb')) output = PdfFileWriter() page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) outputStream = open('result.pdf', 'wb') output.write(outputStream) outputStream.close() ``` |
2
renmu123 2020-11-13 13:19:33 +08:00 via Android
提示一下,pypdf2 已经停止维护了,可以试试 pypdf4 (虽然也快了
|