使用Python将.doc转换为pdf
我现在的任务是把很多.doc文件转换成.pdf格式。而我老板只想让我通过MSWord 2010来完成这个工作。我知道我可以用Python的COM自动化来实现这个,但我不知道该从哪里开始。虽然我试着找了一些教程,但没找到合适的(可能我找到了,但不知道自己在找什么)。
现在我正在阅读这个链接。但我不知道这对我有多大帮助。
14 个回答
24
我试过很多解决方案,但没有一个在Linux系统上运行得很好。
我推荐这个解决方案:
import sys
import subprocess
import re
def convert_to(folder, source, timeout=None):
args = [libreoffice_exec(), '--headless', '--convert-to', 'pdf', '--outdir', folder, source]
process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
filename = re.search('-> (.*?) using filter', process.stdout.decode())
return filename.group(1)
def libreoffice_exec():
# TODO: Provide support for more platforms
if sys.platform == 'darwin':
return '/Applications/LibreOffice.app/Contents/MacOS/soffice'
return 'libreoffice'
然后你可以调用你的函数:
result = convert_to('TEMP Directory', 'Your File', timeout=15)
所有资源:
https://michalzalecki.com/converting-docx-to-pdf-using-python/
53
你可以使用 docx2pdf
这个 Python 包来批量把 docx 文件转换成 pdf 文件。它可以作为命令行工具使用,也可以作为 Python 库来用。使用这个工具需要先安装 Microsoft Office,并且在 Windows 上它会用到 COM 技术,而在 macOS 上则使用 AppleScript(JXA)。
from docx2pdf import convert
convert("input.docx")
convert("input.docx", "output.pdf")
convert("my_docx_folder/")
pip install docx2pdf
docx2pdf input.docx output.pdf
免责声明:我写了这个 docx2pdf 包。 https://github.com/AlJohri/docx2pdf
98
这是一个简单的例子,使用了comtypes库,演示如何将一个文件进行转换,输入和输出的文件名通过命令行参数来提供:
import sys
import os
import comtypes.client
wdFormatPDF = 17
in_file = os.path.abspath(sys.argv[1])
out_file = os.path.abspath(sys.argv[2])
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
你也可以使用pywin32,这个方法和上面差不多,只是:
import win32com.client
然后:
word = win32com.client.Dispatch('Word.Application')