使用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()

效果:

寫入前

寫入后


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM