Python中一些与word模板文件操作相关的库

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类如果需要的话最近回抽时间单独更新一次博客分享这个过程中的收获。

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值