python实现生成word文档,格式转为pdf
使用的是python-docx模块,在生成word文档后转为pdf格式是使用的是docx2pdf中的convert(使用convert转换时,要先创建一个空的pdf文档)
以下是代码:
import datetime
import os
import time
import pythoncom
from django.http import HttpResponse
from docx import Document
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Inches, Cm
from reportlab.pdfgen import canvas
from gistandard import settings
doc_base_path = os.path.join(settings.MEDIA_ROOT, 'doc')#word路径
pdf_base_path = os.path.join(settings.MEDIA_ROOT, 'pdf')#pdf路径
# 创建文档对象
pythoncom.CoInitialize()
document = Document()
header = document.sections[0].header # 获取第一个节的页眉
paragraph = header.paragraphs[0] # 获取页眉的第一个段落
paragraph.add_run('XXXXXXXX作') # 添加页面内容
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT # 靠右
document.add_heading('测试', 0).bold = True # 文档标题
"""p = document.add_paragraph('A plain paragraph having some') # 段落
p.add_run('bold').bold = True # 黑体
p.add_run(' and some ')
p.add_run('italic.').italic = True # 斜体
"""
document.add_heading('一.概览表', level=1) # 一级标题
# document.add_paragraph('Intense quote', style='Intense Quote')
"""
添加表格
"""
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam')
)
table = document.add_table(rows=1, cols=3) # 表格
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
"""
添加图
"""
document.add_heading('二.概览图', level=1) # 一级标题
document.add_paragraph('温度折线图', style='List Number')
document.add_picture('D:\img/img3.jpg', width=Inches(5)) # 图片路径
document.add_page_break() # 分页
# 时间路径
t = datetime.datetime.now().strftime('%Y%m%d%H%M')
dname = t + "demo.docx" # word文档文件名
doc_path = os.path.join(doc_base_path, dname) # word生成路径
# 生成word文档
document.save(doc_path)
pname = t + "demo.pdf" # pdf名
pdf_path = os.path.join(pdf_base_path, pname) # pdf路径
# 创建空pdf
c = canvas.Canvas(pdf_path)
c.showPage()
c.save()
# 判断路径是否存在,存在的话,将.docx文档转为.pdf文档
if os.path.exists(doc_base_path) and os.path.exists(pdf_base_path):
if os.path.isfile(doc_path) and os.path.isfile(pdf_path): # 判断是否存在该word和pdf文件
from docx2pdf import convert
convert(doc_path, pdf_path) # word转pdf
else:
print("文档不存在")
else:
print("路径不存在")
return pdf_path