.doc到pdf使用python

nik*_*nik 34 python pdf automation ms-word win32com

我的任务是将大量的.doc文件转换为.pdf.我的主管要我这样做的唯一方法是通过MSWord 2010.我知道我应该能够通过python COM自动化实现自动化.唯一的问题是我不知道如何以及从哪里开始.我试着寻找一些教程,但却找不到(可能是我可能有,但我不知道我在找什么).

现在我正在阅读这个.不知道这会有多大用处.

Ste*_*ven 58

一个使用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()
Run Code Online (Sandbox Code Playgroud)

你也可以使用pywin32,除了:

import win32com.client
Run Code Online (Sandbox Code Playgroud)

然后:

word = win32com.client.Dispatch('Word.Application')
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用 linux 服务器,而这些库在 linux 中不起作用.. 有没有其他方法可以使其在 linux 中工作 (5认同)
  • 我已经设法让它适用于 powerpoint 文档。使用“Powerpoint.Application”、“Presentations.Open”和“FileFormat=32”。 (4认同)
  • 对于许多文件,考虑设置:`word.Visible = False`以节省时间和处理word文件(MS word不会以这种方式显示,代码将在后台运行) (3认同)
  • 这正是我所寻找的.谢谢 :) (2认同)
  • 经过8年的开发,正是这个答案让我感到很不舒服,因为我不在Windows上! (2认同)
  • 有没有办法只使用文件对象并避免这些文件保存? (2认同)

Al *_*hri 18

您可以使用docx2pdfpython 包将 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/")
Run Code Online (Sandbox Code Playgroud)
pip install docx2pdf
docx2pdf input.docx output.pdf
Run Code Online (Sandbox Code Playgroud)

免责声明:我编写了 docx2pdf 包。https://github.com/AlJohri/docx2pdf

  • 不幸的是,它需要安装 Microsoft Office,因此仅适用于 Windows 和 macOS。 (15认同)

小智 12

我测试了许多解决方案,但没有一个在 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'
Run Code Online (Sandbox Code Playgroud)

然后你调用你的函数:

result = convert_to('TEMP Directory',  'Your File', timeout=15)
Run Code Online (Sandbox Code Playgroud)

所有资源:

https://michalzalecki.com/converting-docx-to-pdf-using-python/

  • 这没有使用 Python,这只是从 python 脚本运行 libre office exe。 (2认同)

Yan*_*ang 8

我已经解决了这个问题半天了,所以我想我应该分享一些关于这个问题的经验.史蒂文的答案是对的,但它会在我的电脑上失败.这里有两个关键点可以解决它:

(1).我第一次创建'Word.Application'对象时,我应该在打开任何文档之前使它(单词app)可见.(实际上,即使我自己也无法解释为什么会这样.如果我不在我的计算机上执行此操作,当我尝试在隐形模型中打开文档时程序将崩溃,然后'Word.Application'对象将被删除OS.)

(2).在执行(1)之后,程序有时会运行良好但可能经常失败.崩溃错误"COMError: (-2147418111, 'Call was rejected by 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 
Run Code Online (Sandbox Code Playgroud)


lxx*_*lxx 7

unoconv(用python编写)和作为无头守护进程运行的openoffice。 http://dag.wiee.rs/home-made/unoconv/

适用于 doc、docx、ppt、pptx、xls、xlsx。如果您需要在服务器上转换文档或保存/转换为某些格式,则非常有用

  • 您可以包含一个示例代码来展示如何从 python 脚本执行此操作(“import unoconv”“unoconv.dosomething(...)”)吗?该文档仅显示如何从命令行执行此操作。 (2认同)

小智 5

作为 SaveAs 函数的替代方法,您还可以使用 ExportAsFixedFormat,它使您可以访问通常在 Word 中看到的 PDF 选项对话框。有了它,您可以指定书签和其他文档属性。

doc.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
    );
Run Code Online (Sandbox Code Playgroud)

函数参数的完整列表是:“OutputFileName”、“ExportFormat”、“OpenAfterExport”、“OptimizeFor”、“Range”、“From”、“To”、“Item”、“IncludeDocProps”、“KeepIRM”、“CreateBookmarks” ', 'DocStructureTags', 'BitmapMissingFonts', 'UseISO19005_1', 'FixedFormatExtClassPtr'