有没有办法将docx转换为pdf而无需在python中安装word?

问题描述

我正在运行脚本的计算机没有 MS Office。有没有办法在没有它的情况下转换它们?

解决方法

PythonAnywhere 有非常有用的帮助页面,LibreOffice 也可以使用。

如果你安装 LibreOffice,你只需要这个代码:

from subprocess import  Popen
LIBRE_OFFICE = r"C:\Program Files\LibreOffice\program\soffice.exe"

def convert_to_pdf(input_docx,out_folder):
    p = Popen([LIBRE_OFFICE,'--headless','--convert-to','pdf','--outdir',out_folder,input_docx])
    print([LIBRE_OFFICE,input_docx])
    p.communicate()


sample_doc = 'file.docx'
out_folder = 'some_folder'
convert_to_pdf(sample_doc,out_folder)