word转pdf

很多人在工作经常会遇到word转pdf功能,word转pdf还是比较复杂,网上各种包,如python的各种转换包,其实是存在很多问题

的,尤其是对比较复杂的格式,真正的还的是调用组件来转换,这里介绍的是LibreOffice,以MAC环境为例,没有装LibreOffice的

可以通过brew install LibreOffice 安装,安装成功具体应用代码如下:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:Eric.yue
 4 
 5 from subprocess import Popen, PIPE
 6 def convert(src, dst):
 7     d = {'src': src, 'dst': dst}
 8 
 9     command = '/Applications/LibreOffice.app/Contents/MacOS/soffice --headless --invisible --convert-to pdf %(src)s --outdir %(dst)s' % d
10 
11     process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True) # I am aware of consequences of using `shell=True`
12     out, err = process.communicate()
13     errcode = process.returncode
14     if errcode != 0:
15         raise Exception(err)
16 
17 if __name__ == '__main__':
18     src = "template.docx"
19     dst = "output_folder"
20     convert(src, dst)

如果是在Linux上应用请直接将/Applications/LibreOffice.app/Contents/MacOS/soffice修改libreoffice

前提是你的事先安装好Libreoffice

posted @ 2019-04-11 13:12  北京流浪儿  阅读(278)  评论(0编辑  收藏  举报