我正在处理一个试图开发一个web-app的问题,其中一部分将上传的docx文件转换为pdf文件(经过一些处理)。 使用python-docx
和其他方法,我不需要安装word的windows机器,甚至不需要linux上的libreoffice,用于大部分处理(我的web服务器是pythonanywhere-linux,但没有libreoffice并且没有sudo
或apt install
权限)。 但转换为pdf似乎需要其中之一。 从探索这里和其他地方的问题,这是我到目前为止所拥有的:
import subprocess
try:
from comtypes import client
except ImportError:
client = None
def doc2pdf(doc):
"""
convert a doc/docx document to pdf format
:param doc: path to document
"""
doc = os.path.abspath(doc) # bugfix - searching files in windows/system32
if client is None:
return doc2pdf_linux(doc)
name, ext = os.path.splitext(doc)
try:
word = client.CreateObject('Word.Application')
worddoc = word.Documents.Open(doc)
worddoc.SaveAs(name + '.pdf', FileFormat=17)
except Exception:
raise
finally:
worddoc.Close()
word.Quit()
def doc2pdf_linux(doc):
"""
convert a doc/docx document to pdf format (linux only, requires libreoffice)
:param doc: path to document
"""
cmd = 'libreoffice --convert-to pdf'.split() + [doc]
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
p.wait(timeout=10)
stdout, stderr = p.communicate()
if stderr:
raise subprocess.SubprocessError(stderr)
如您所见,一种方法需要comtypes
,另一种方法需要libreoffice
作为子进程。 除了切换到更复杂的托管服务器之外,还有什么解决方案吗?
您可以使用的另一个是libreoffice,但正如第一响应者所说,质量永远不会像使用实际的comtypes那样好。
无论如何,在您安装了libreoffice之后,这里是执行此操作的代码。