You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask部署IIS后docx转PDF遇COM服务器执行失败问题求助

Flask应用部署IIS后PDF转换失败(WinError -2146959355)

开发了一个Flask应用,包含生成docx文档并转换为PDF的功能。本地运行时一切正常,可成功生成PDF;但将应用通过FastCGI模块部署到IIS服务器后,docx能正常生成,PDF转换却失败,抛出WinError -2146959355(服务器执行失败)的错误。已为DefaultApplicationPool和IIS_IUSR赋予Word及PDF相关权限,使用comtypes.client和docx2pdf库均出现相同错误。

生成并转换文档的函数代码

def CreateApplication(file,replacements,serialnum):

    document=Document(file)
    for para in document.paragraphs:
        # 遍历段落中的run
        for run in para.runs:
            # 检查run文本是否是替换字典中的关键字
            if run.text in replacements:
                # 替换关键字并保留样式
                run.text = replacements[run.text]
    for table in document.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        for keyword, value in replacements.items():
                            if keyword in run.text:
                                # 替换文本中的关键字
                                run.text = run.text.replace(keyword, value)
    document.save(f'files/{serialnum}/MainFiles/Application{serialnum}.docx')
    docx_output_path=f'files/{serialnum}/MainFiles/Application{serialnum}.docx'
    pdf_input_path = docx_output_path
    
    # 指定PDF输出路径
    pdf_output_path = os.path.splitext(pdf_input_path)[0] + '.pdf'
    
    # 转换docx到pdf
    convert(pdf_input_path, pdf_output_path)

Flask路由调用代码

@app.route('/submitapplication/<serialnumber>',methods=['POST','GET'])
def submit(serialnumber):
    st = time.time()
    print('iam in')
    datacoming=request.get_json()
    print(datacoming)
    project_describtion=json.loads(datacoming)
    project_describtion['Statue_of_Project']='Application pending'
    current_date = datetime.now()
    formatted_date = current_date.strftime("%Y-%m-%d")
    project_describtion['DateofApplication'] = formatted_date
    print(project_describtion)
    pidata = Search_in_Company(session['user'], session['password'], session['serverip'], session['companyid'])
    project_describtion.update(pidata)
    '''
    编写SQL代码将字典内容上传到对应行
    '''
    project_describtion['Project_Serial_Number']=serialnumber
    #CreateApplication('LPG application General.docx',project_describtion,serialnumber)

    # 尝试用线程在另一个进程运行转换
    Application=threading.Thread(target=CreateApplication,args=('LPG application General.docx',project_describtion,serialnumber))
    Application.start()


    # 计算执行时间
    Update_case(session['user'],session['password'],session['serverip'],session['currentserial'],session['companyid'],project_describtion)
    et = time.time()
    elapsed_time = et - st
    print('Execution time:', elapsed_time, 'seconds')
    return jsonify({'url': url_for('home')})

使用comtypes.client时的报错

Exception on /submitapplication/JO-2023JL030039 [POST]
Traceback (most recent call last):
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\inetpub\wwwroot\flpgproj\main.py", line 404, in submit
    CreateApplication('LPG application General.docx',project_describtion,serialnumber)
  File "C:\inetpub\wwwroot\flpgproj\CreateFiles.py", line 136, in CreateApplication
    convert_to_pdf(pdf_input_path, pdf_output_path)
  File "C:\inetpub\wwwroot\flpgproj\CreateFiles.py", line 35, in convert_to_pdf
    word=comtypes.client.CreateObject('Word.Application')
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\comtypes\client\__init__.py", line 215, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\comtypes\__init__.py", line 1264, in CoCreateInstance
    _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
  File "_ctypes/callproc.c", line 1000, in GetResult
OSError: [WinError -2146959355] Server execution failed

使用docx2pdf时的报错

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\flask\app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\inetpub\wwwroot\flpgproj\main.py", line 404, in submit
    CreateApplication('LPG application General.docx',project_describtion,serialnumber)
  File "C:\inetpub\wwwroot\flpgproj\CreateFiles.py", line 136, in CreateApplication
    convert(pdf_input_path, pdf_output_path)
  File "C:\Python\python311\Lib\site-packages\docx2pdf\__init__.py", line 106, in convert
    return windows(paths, keep_active)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\docx2pdf\__init__.py", line 19, in windows
    word = win32com.client.Dispatch("Word.Application")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\python311\Lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_error: (-2146959355, 'Server execution failed', None, None)

内容的提问来源于stack exchange,提问作者baraatemp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:08:03