'NoneType' 对象在 Windows 上没有属性 'SaveAs' docx2pdf

问题描述

from docx2pdf import convert
import pythoncom 

#flask rest api
@app.route('/api_v1/get_pdf/',methods=['GET'])
def get_pdf():
    if threading.currentThread ().getName () != 'MainThread':
        pythoncom.CoInitialize () 
    convert(in_word,out_pdf )

我正在使用 docx2pdf 在 python 中将 docx 文件转换为 pdf,我的脚本需要在 windows 启动时执行(无需登录 windows )。在这种模式下,脚本在转换为 pdf 'nonetype' object has no attribute 'SaveAs' 时会引发错误。我不知道问题出在哪里,但我认为这是因为某些服务在登录到 Windows 之前无法正常工作,但是如果我在登录到 Windows 后运行脚本,则可以正常工作。那么如何在登录 Windows 之前使脚本正常工作?

追溯:

'nonetype' object has no attribute 'SaveAs'
Traceback (most recent call last):
File "D:\xxxx\main.py",line 746,in get_pdf
convert(in_word,out_pdf )
File "C:\python38\lib\site-packages\docx2pdf\__init__.py",line 106,in convert
return windows(paths,keep_active)
File "C:\python38\lib\site-packages\docx2pdf\__init__.py",line 33,in windows
doc.SaveAs(str(pdf_filepath),FileFormat=wdFormatPDF)
AttributeError: 'nonetype' object has no attribute 'SaveAs'

解决方法

docx2pdf 通过运行 Microsoft Word 应用程序进行转换。如果没有用户登录,Word 将无法启动,即使它不会显示 UI。您必须找到另一个不使用 Word 的 docx 转换器。有几个选项,包括 pandoc。