使用python往已有内容的PDF文件写入数据

只使用reportlab库好像没法在已经有内容的PDF页面中写入数据,只能生成一个空的PDF文件再写入。所以这里我是配合pdfrw库来实现的。具体见示例

from reportlab.pdfgen.canvas import Canvas
from pdfrw import PdfReader
from pdfrw.buildxobj import pagexobj
from pdfrw.toreportlab import makerl
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import registerFont


def pdf_write(input_file, output_file=None):

    text_dic = [
        ["ABCDEFG HIJKLMN", 90, 757, 12],
        ["123456789123456789", 90, 738, 10]
    ]

    if not output_file:
        output_file = f'{os.path.splitext(input_file)[0]}_new.pdf'
    registerFont(TTFont('yh', 'msyh.ttf'))  # 设置文字字体

    template = PdfReader(input_file)
    canvas = Canvas(output_file)

    template_obj0 = pagexobj(template.pages[0])
    obj0_name = makerl(canvas, template_obj0)
    canvas.doForm(obj0_name)

    for value in text_dic:
        canvas.setFont("yh", value[3])  # 设置字号
        canvas.drawString(value[1], value[2], value[0])

    canvas.showPage()  # 关闭当前页,开始新页
    template_obj1 = pagexobj(template.pages[1])
    obj1_name = makerl(canvas, template_obj1)
    canvas.doForm(obj1_name)

    canvas.save()

效果:

写入前

写入后

posted @ 2022-03-11 15:02  Rong_Z  阅读(507)  评论(0编辑  收藏  举报