我被分配任务将大量的.doc文件转换成.pdf格式。而我的主管只想让我使用MSWord 2010来完成此任务。我知道应该可以通过python COM自动化来实现这一过程。唯一的问题是我不知道该从哪里开始以及如何操作。我尝试搜索一些教程,但没有找到任何有用的信息(也许我已经找到了,但我不知道我在寻找什么)。
目前,我正在阅读这个网站。不知道这对我有多大帮助。
这是一个使用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')
您可以使用docx2pdf
Python包批量将docx转换为pdf。 它可以用作CLI和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
我尝试了许多解决方案,但是它们中没有一个在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/
我已经花了半天的时间研究这个问题,所以我认为我应该分享一些我在这方面的经验。Steven的答案是正确的,但它在我的电脑上会失败。要解决这个问题有两个关键点:
(1). 第一次创建 'Word.Application' 对象时,我应该在打开任何文档之前使其 (word app) 可见。 (实际上,即使我自己也无法解释为什么这样做会起作用。如果我在我的电脑上不这样做,在隐身模式下尝试打开文档时程序会崩溃,然后 'Word.Application' 对象将被操作系统删除。)
(2). 在完成第一步后,程序有时可能表现良好,但也可能经常失败。崩溃错误 "COMError: (-2147418111, 'Callee 拒绝了调用', (None, None, None, 0, None))"
表明 COM 服务器可能无法及时响应。因此,在试图打开文档之前,我添加了一个延迟。
完成这两个步骤后,程序将完美地工作,不再出现故障。演示代码如下。如果您遇到相同的问题,请尝试遵循这两个步骤。希望对您有所帮助。
import os
import comtypes.client
import time
wdFormatPDF = 17
# absolute path is needed
# be careful about the slash '\', use '\\' or '/' or raw string r"..."
in_file=r'absolute path of input docx file 1'
out_file=r'absolute path of output pdf file 1'
in_file2=r'absolute path of input docx file 2'
out_file2=r'absolute path of outputpdf file 2'
# print out filenames
print in_file
print out_file
print in_file2
print out_file2
# create COM object
word = comtypes.client.CreateObject('Word.Application')
# key point 1: make word visible before open a new document
word.Visible = True
# key point 2: wait for the COM Server to prepare well.
time.sleep(3)
# convert docx file 1 to pdf file 1
doc=word.Documents.Open(in_file) # open docx file 1
doc.SaveAs(out_file, FileFormat=wdFormatPDF) # conversion
doc.Close() # close docx file 1
word.Visible = False
# convert docx file 2 to pdf file 2
doc = word.Documents.Open(in_file2) # open docx file 2
doc.SaveAs(out_file2, FileFormat=wdFormatPDF) # conversion
doc.Close() # close docx file 2
word.Quit() # close Word Application
unoconv
是一个用Python编写的工具,它以无头守护进程方式运行OpenOffice。
https://github.com/unoconv/unoconv
http://dag.wiee.rs/home-made/unoconv/
对于doc、docx、ppt、pptx、xls和xlsx格式文件非常有效。
如果你需要在服务器上转换文档或保存/转换特定格式,那么这个工具非常有用。
import unoconv
unoconv.dosomething(...)
)?文档中只展示了如何通过命令行来实现。 - Basjdoc.ExportAsFixedFormat(OutputFileName=pdf_file,
ExportFormat=17, #17 = PDF output, 18=XPS output
OpenAfterExport=False,
OptimizeFor=0, #0=Print (higher res), 1=Screen (lower res)
CreateBookmarks=1, #0=No bookmarks, 1=Heading bookmarks only, 2=bookmarks match word bookmarks
DocStructureTags=True
);
完整的函数参数列表如下:'OutputFileName','ExportFormat','OpenAfterExport','OptimizeFor','Range','From','To','Item','IncludeDocProps','KeepIRM','CreateBookmarks','DocStructureTags','BitmapMissingFonts','UseISO19005_1','FixedFormatExtClassPtr'
如果你不介意使用PowerShell,可以看一下这篇Hey, Scripting Guy! article。所呈现的代码可以采用WdSaveFormat
枚举值中的wdFormatPDF
(请参见此处)。
这篇博客文章提供了同样想法的另一种实现。
import os, re, time, datetime, win32com.client
def print_to_Bullzip(file):
util = win32com.client.Dispatch("Bullzip.PDFUtil")
settings = win32com.client.Dispatch("Bullzip.PDFSettings")
settings.PrinterName = util.DefaultPrinterName # make sure we're controlling the right PDF printer
outputFile = re.sub("\.[^.]+$", ".pdf", file)
statusFile = re.sub("\.[^.]+$", ".status", file)
settings.SetValue("Output", outputFile)
settings.SetValue("ConfirmOverwrite", "no")
settings.SetValue("ShowSaveAS", "never")
settings.SetValue("ShowSettings", "never")
settings.SetValue("ShowPDF", "no")
settings.SetValue("ShowProgress", "no")
settings.SetValue("ShowProgressFinished", "no") # disable balloon tip
settings.SetValue("StatusFile", statusFile) # created after print job
settings.WriteSettings(True) # write settings to the runonce.ini
util.PrintFile(file, util.DefaultPrinterName) # send to Bullzip virtual printer
# wait until print job completes before continuing
# otherwise settings for the next job may not be used
timestamp = datetime.datetime.now()
while( (datetime.datetime.now() - timestamp).seconds < 10):
if os.path.exists(statusFile) and os.path.isfile(statusFile):
error = util.ReadIniString(statusFile, "Status", "Errors", '')
if error != "0":
raise IOError("PDF was created with errors")
os.remove(statusFile)
return
time.sleep(0.1)
raise IOError("PDF creation timed out")
word.Visible = False
以节省处理 Word 文件所需的时间和资源(这样 MS Word 将不会显示,代码将在后台运行) - ecoePowerpoint.Application
、Presentations.Open
和FileFormat=32
。 - Snorfalorpagus