使用Python将.doc转换为.pdf

77

我被分配任务将大量的.doc文件转换成.pdf格式。而我的主管只想让我使用MSWord 2010来完成此任务。我知道应该可以通过python COM自动化来实现这一过程。唯一的问题是我不知道该从哪里开始以及如何操作。我尝试搜索一些教程,但没有找到任何有用的信息(也许我已经找到了,但我不知道我在寻找什么)。

目前,我正在阅读这个网站。不知道这对我有多大帮助。

14个回答

2

我曾经使用该解决方案,但需要搜索所有.docx、.dotm、.docm、.odt、.doc或.rtf文件,然后将它们全部转换为.pdf(使用Python 3.7.5版本)。希望这能够起作用...

import os
import win32com.client

wdFormatPDF = 17

for root, dirs, files in os.walk(r'your directory here'):
    for f in files:

        if  f.endswith(".doc")  or f.endswith(".odt") or f.endswith(".rtf"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                word = win32com.client.Dispatch('Word.Application')
                word.Visible = False
                doc = word.Documents.Open(in_file)
                doc.SaveAs(os.path.join(root,f[:-4]), FileFormat=wdFormatPDF)
                doc.Close()
                word.Quit()
                word.Visible = True
                print ('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        elif f.endswith(".docx") or f.endswith(".dotm") or f.endswith(".docm"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                word = win32com.client.Dispatch('Word.Application')
                word.Visible = False
                doc = word.Documents.Open(in_file)
                doc.SaveAs(os.path.join(root,f[:-5]), FileFormat=wdFormatPDF)
                doc.Close()
                word.Quit()
                word.Visible = True
                print ('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        else:
            pass

使用try和except是为了那些我无法读取的文档,它不会退出代码直到最后一个文档。


你正在导入什么? - not2qubit

1
你应该从调查所谓的虚拟 PDF 打印驱动程序开始。一旦你找到了一个,你就应该能够编写批处理文件,将你的 DOC 文件打印成 PDF 文件。你可能也可以用 Python 来做这个(设置打印机驱动程序输出并在 MSWord 中发出文档/打印命令,后者可以使用命令行 AFAIR)。

0
import docx2txt
from win32com import client

import os

files_from_folder = r"c:\\doc"

directory = os.fsencode(files_from_folder)

amount = 1

word = client.DispatchEx("Word.Application")
word.Visible = True

for file in os.listdir(directory):
    filename = os.fsdecode(file)
    print(filename)

    if filename.endswith('docx'):
        text = docx2txt.process(os.path.join(files_from_folder, filename))

        print(f'{filename} transfered ({amount})')
        amount += 1
        new_filename = filename.split('.')[0] + '.txt'

        try:
            with open(os.path.join(files_from_folder + r'\txt_files', new_filename), 'w', encoding='utf-8') as t:
                t.write(text)
        except:
            os.mkdir(files_from_folder + r'\txt_files')
            with open(os.path.join(files_from_folder + r'\txt_files', new_filename), 'w', encoding='utf-8') as t:
                t.write(text)
    elif filename.endswith('doc'):
        doc = word.Documents.Open(os.path.join(files_from_folder, filename))
        text = doc.Range().Text
        doc.Close()

        print(f'{filename} transfered ({amount})')
        amount += 1
        new_filename = filename.split('.')[0] + '.txt'

        try:
            with open(os.path.join(files_from_folder + r'\txt_files', new_filename), 'w', encoding='utf-8') as t:
                t.write(text)
        except:
            os.mkdir(files_from_folder + r'\txt_files')
            with open(os.path.join(files_from_folder + r'\txt_files', new_filename), 'w', encoding='utf-8') as t:
                t.write(text)
word.Quit()

源代码,请见此处:

https://neculaifantanaru.com/en/python-full-code-how-to-convert-doc-and-docx-files-to-pdf-from-the-folder.html


你好,欢迎来到SO。请在导入的软件包中包含链接,并解释一下你的解决方案与已经提到的方案有何不同和更好之处。 - not2qubit

-7
我建议您忽略您的主管,使用具有Python API的OpenOffice。 OpenOffice内置了对Python的支持,并且有人为此创建了一个特定的库(PyODConverter)。
如果他对输出不满意,请告诉他用Word可能需要花费您数周的时间。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接