Windows下使用Python进行WORD、PPT、EXCEL转PDF
Windows下django中进行word、ppt、Excel转PDF,借助office插件
近日,在开发过程中遇到需要将django上传的word、ppt、Excel转为PDF并保存的需求,故记录一下。
环境依赖Windows office、Python包(pywin32)
源码
from win32com import client
import pythoncom
from win32com.client import gencache, Dispatch, constants
def convert(input,output):
# 初始化
pythoncom.CoInitialize()
if input.endswith('.doc') or input.endswith('.docx'):
doc2pdf(input, output)
pythoncom.CoUninitialize() # 释放资源
elif input.endswith('.ppt') or input.endswith('.pptx'):
ppt2pdf(input, output)
pythoncom.CoUninitialize()
elif input.endswith('xls') or input.endswith('.xlsx'):
excel2pdf(input, output)
pythoncom.CoUninitialize()
else:
print("文档格式错误")
def GenerateSupport():
# enable python COM support for Word 2007
# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
# 以下数值根据自己电脑生成对应的,然后替换,我的是office 2016
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 7)
# https://stackoverflow.com/questions/47608506/issue-in-using-win32com-to-access-excel-file
def doc2pdf(input, output):
GenerateSupport()
w = client.Dispatch("Word.Application")
try:
doc = w.Documents.Open(input)
doc.ExportAsFixedFormat(output, client.constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
except Exception as e:
print("转换异常,异常是:{}".format(e))
finally:
w.Quit(constants.wdDoNotSaveChanges)
def ppt2pdf(input, output):
p = client.Dispatch("PowerPoint.Application")
ppt = p.Presentations.Open(input, False, False, False)
ppt.ExportAsFixedFormat(output, 2, PrintRange=None)
p.Quit()
def excel2pdf(input, output):
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(input)
books.ExportAsFixedFormat(0, output)
xlApp.Quit()
参数说明:
input: 输入文件的路径
output: 输出的PDF保存路径
注意:一定要有office,且是激活的,最好将office设为默认程序,防止提示框未关闭的时候转码会出现报错,另外,该插件只能单进程调用。如有大量文件需要转,只能一个一个转,因技术水平有限,目前是将用户上传的文件传到了一个队列中,然后用定时器定时从队列中取出文件处理。暂时满足需求!!!