from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH #设置行列的数量
from docx.shared import Pt #磅数
from docx.oxml.ns import qn #中文格式
from docx.shared import Inches #图片尺寸
#以上是docx库中需要用到的部分
from win32com.client import Dispatch,constants,gencache
import datetime
import os
import time
price = input(‘请输入今日价格:’)
company_list = [‘客户1’,‘客户2’,‘客户3’,‘客户4’,‘客户5’,‘客户6’,‘客户7’,‘客户8’,‘客户9’,‘客户10’,‘客户11’,‘客户12’]
#time 有整理格式的功能
today = time.strftime("%Y{y}%m{m}%d{d}",time.localtime()).format(y=‘年’,m=‘月’,d=‘日’)
for i in company_list:
document = Document()
#设置文档的基础字体
document.styles['Normal'].font.name = u'宋体'
document.styles['Normal'].font.size = Pt(14)
#设置文档的基础中文字体
document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体')
#z在文件最上头插入图片作为文件红头,宽度为6英寸
document.add_picture('however.png',width=Inches(6))
# 初始化建立第一个自然段
p1 = document.add_paragraph()
# 对齐方式为居中,没有这句话的默认左对齐
p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 不同要求的字体可以设置很多run
run1 = p1.add_run('关于下达%s产品价格的通知' % (today))
# 字体
# 设置西文字体
run1.font.name = '微软雅黑'
# 设置中文字体
run1._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
# 字的磅数、大小
run1.font.size = Pt(21)
# 设置加粗
run1.font.bold = True
# 段后距离5磅
p1.space_after = Pt(5)
# 短前距离5磅
p1.space_after = Pt(5)
if os.path.exists(r"C:\Users\Polyxena\Desktop\untitled1\%s-价格通知.docx" %i):
#目的是避免有重复的文件
os.remove("C:/Users/Polyxena/Desktop/untitled1/%s-价格通知.docx" % i)
document.save("C:/Users/Polyxena/Desktop/untitled1/%s-价格通知.docx" % i)
docx_path = 'C:/Users/Polyxena/Desktop/untitled1/%s-价格通知.docx' % i
pdf_path = 'C:/Users/Polyxena/Desktop/untitled1/%s-价格通知.pdf' % i
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}',0,8,4)
wd = Dispatch("Word.Application")
doc = wd.Documents.Open(docx_path,ReadOnly=1)
doc.ExportAsFixedFormat(pdf_path,constants.wdExportFormatPDF,Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks = constants.wdExportCreateHeadingBookmarks)
wd.Quit(constants.wdDoNotSaveChanges)
time.sleep(5)
os.remove(r"C:\Users\Polyxena\Desktop\untitled1\%s-价格通知.docx" % i)