更新:以下模块已经上传到pypi,可以直接使用
pip install certimaker
下载certimaker模块,然后在本地代码中使用以下代码就可以快速生成奖状
from certimaker.certimaker import make_certificate
make_certificate('王大雷','国家奖学金')
完成这个小项目需要掌握以下知识点:
1.第三方模块的import使用方法
2.word文档的docx模型(doc/paragraph/run三层结构)
3.类和函数写法(OOP)基础
4.pinyin、datetime模块的基本使用方法
代码如下:
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
import pinyin
import datetime
BLACK = RGBColor(0,0,0)
RED = RGBColor(255,0,0)
GREEN = RGBColor(0,255,0)
BLUE = RGBColor(0,0,255)
TODATE = datetime.datetime.now().strftime('%Y.%m.%d')
THISY = datetime.datetime.now().strftime('%Y')
LASTY = str(int(THISY)-1)
class DocWriter:
def __init__(self,name,award):
self.doc = Document()
self.name = name
self.award = award
def new_para(self):
self.para = self.doc.add_paragraph()
def write_run(self, content, fontsize = 25, fontname = '华文中宋',
alignment = WD_ALIGN_PARAGRAPH.LEFT, color = BLACK,
underline = False, bold = False):
para = self.para
run = para.add_run(content)
run.font.size = Pt(fontsize)
run.font.name = fontname
run.font.underline = underline
run.font.bold = bold
r = run._element.rPr.rFonts
r.set(qn('w:eastAsia'),fontname)
para.alignment = alignment
run.font.color.rgb = color
def signature(self,sign):
self.new_para()
self.write_run(sign,alignment=WD_ALIGN_PARAGRAPH.RIGHT)
self.new_para()
self.write_run(TODATE,alignment=WD_ALIGN_PARAGRAPH.RIGHT)
def save_doc(self):
pyname = pinyin.get(self.name, format='strip', delimiter="")
pyaward= pinyin.get(self.award,format='strip', delimiter="")
filename = pyname + '_'+ pyaward + '.docx'
self.doc.save(filename)
def make_certificate(name,award):
awardoc = DocWriter(name,award)
awardoc.new_para()
awardoc.write_run('奖 状', fontsize = 50,alignment= WD_ALIGN_PARAGRAPH.CENTER,color = RED,bold=True)
awardoc.new_para()
awardoc.write_run(' '*2+name+' '*2,fontsize = 30,underline = True,bold=True)
awardoc.write_run(' 同学:',fontsize = 30)
awardoc.new_para()
awardoc.write_run(f'\t你在{LASTY}—{THISY}年度表现优异,被授予')
awardoc.write_run(' '*2 + award + ' '*2, underline=True, bold=True)
awardoc.write_run('荣誉称号。')
awardoc.new_para()
awardoc.write_run('\t特发此证,以资鼓励!')
awardoc.signature('python大学')
awardoc.save_doc()
name = '李雷'
award = '三好学生'
make_certificate(name,award)
运行之后会生成.docx类型的word文档如下:
打开之后,我们可以看到成功生成了一张奖状:
我们把以上代码保存为模块’docxclass.py’,就可以在其他的python代码中调用这个模块里面定义的函数make_certificate(),我们新建一个新的python文件,写入以下代码:
from docxclass import make_certificate
award_dict = {
'李雷':'三好学生',
'韩梅梅':'学习积极分子',
'Jim':'体育积极分子',
'Kate':'文艺积极分子',
'Lucy':'劳动积极分子',
'Lily':'德育积极分子',
}
for name,award in award_dict.items():
make_certificate(name,award)
这样就可以批量生成奖状了:
我们随意打开其中的一个,就可以得到想要的奖状效果: