0

以下代码是使用 comtypes 模块将 docx 转换为 pdf。

import os
from comtypes.client import CreateObject

newdir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
if not os.path.exists(newdir):
    os.makedirs(newdir)

file_name = os.path.join(newdir,test.docx')
print(file_name)
pdf_filename = file_name.split(".docx")[0] + ".pdf"
pdf_file = os.path.join(newdir, pdf_filename)    
wdToPDF = CreateObject("Word.Application")
wdFormatPDF = 17

if os.path.exists(pdf_file):
    os.remove(pdf_file)

pdfCreate = wdToPDF.Documents.Open(file_name)
pdfCreate.SaveAs(pdf_file, wdFormatPDF)
wdToPDF.Documents.Close()

这段代码之前有一些警告,我能够得到输出 pdf 文件,但现在它突然停止在 pycharm 上工作。错误是 -

CRITICAL: [WinError -2147221008] CoInitialize has not been called

警告:

[2021-12-02 15:56:09,253] None requested None INFO: Imported existing <module 'comtypes.gen' from 'C:\\Users\\XYZ\\TestProj\\venv\\lib\\site-packages\\comtypes\\gen\\__init__.py'>
[2021-12-02 15:56:09,253] None requested None INFO: Imported existing <module 'comtypes.gen' from 'C:\\Users\\XYZ\\TestProj\\\\venv\\lib\\site-packages\\comtypes\\gen\\__init__.py'> [in C:\Users\XYZ\TestProj\venv\lib\site-packages\comtypes\client\_code_cache.py:95]
[2021-12-02 15:56:09,253] None requested None INFO: Using writeable comtypes cache directory: 'C:\Users\XYZ\TestProj\venv\lib\site-packages\comtypes\gen'
[2021-12-02 15:56:09,253] None requested None INFO: Using writeable comtypes cache directory: 'C:\Users\XYZ\TestProj\venv\lib\site-packages\comtypes\gen' [in C:\Users\XYZ\TestProj\venv\lib\site-packages\comtypes\client\_code_cache.py:72]

我已经安装了 comtypes版本 1.1.7,因为它支持跨平台。另外,我不想使用win32com模块,因为我也想在 Linux 和 Mac os 上运行它。

有些人建议导入pythoncom模块并添加pythoncom.CoInitialize()代码,但这也没有用。

我在这里做错了什么?

4

0 回答 0