Python中處理Word的一些庫
最近由于需要需要對word模板進行一些操作,并且將最后處理之后的word檔案轉換成pdf格式輸出,因此寫個文章來記錄一下這段時間的學習與識訓,下面就簡單的列出此次使用到的一些Python庫,
1、docxtpl,用于操作word模板
先看效果:
這是處理之前的word模板

這是處理后的word,看起來是不是很神奇呢,試想一下如果有100份甚至更多的需求,是不是只需要一個簡單的for回圈就解決了呢:

下面直接上代碼揭開它的神秘面紗:
from docxtpl import DocxTemplate
from docx.shared import Mm, Pt
tpl = DocxTemplate('demo.docx')
# 對要插入的圖片進行處理,這里的docxtpl,默認只有InlineImage(嵌入式插入圖片,引數也只有width和height設定圖片寬高)
# AnchorImage是自己處理之后的可以插入浮動圖片的類pos_x和pos_y用于定位圖片位置,
img2_path = docxtpl.AnchorImage(tpl, '2.png', width=Mm(15), height=Mm(10), pos_x=Pt(480), pos_y=Pt(490))
img3_path = docxtpl.AnchorImage(tpl, '3.png', width=Mm(15), height=Mm(10), pos_x=Pt(460), pos_y=Pt(530))
img4_path = docxtpl.AnchorImage(tpl, '4.png', width=Mm(15), height=Mm(10), pos_x=Pt(460), pos_y=Pt(570))
# 定義模板的替換資料
content = {
"arr_year" : 2021, "arr_month" : 4, "arr_day" : 15,
"test_year" : 2021, "test_month" : 4, "test_day" : 22,
"img2" : img2_path,
"img3" : img3_path,
"img4" : img4_path
}
tpl.render(content)
tpl.save('save.docx')
2、reportlab和docx2pdf,用于word轉pdf格式
廢話不說,直接上代碼,
from reportlab.pdfgen import canvas
from docx2pdf import convert
# 已有的word檔案
docx_path = 'demo.docx'
# 定義生成的pdf檔案路徑
pdf_path = 'demo.pdf'
# 先創建pdf檔案
c = canvas.Canvas(pdf_path)
c.showPage()
c.save()
if os.path.exists(docx_path) and os.path.exists(pdf_path):
convert(docx_path, pdf_path)
else:
print('路徑不存在^_^,')
好了,今天就分享這些內容啦,關于docxtpl中提到的AnchorImage類如果需要的話最近回抽時間單獨更新一次博客分享這個程序中的識訓,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/300833.html
標籤:其他
