COM问题,当我运行我的 flask 代码在IIS上使用docx到pdf转换时

olmpazwi  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个 flask 应用程序,其中包含一个功能,以创建一个docx文档,然后将其转换为pdf,当我在本地计算机上运行代码时,一切正常,并创建了pdf文档,但当我在部署计算机上的IIS上托管应用程序时,使用fastcgi模块,它工作正常,并创建了docx文档,但由于错误而没有创建pdf文档,下面是创建docx文档并使用docx2pdf库转换为pdf的函数:

def CreateApplication(file,replacements,serialnum):

    document=Document(file)
    for para in document.paragraphs:
        # Iterate through the runs in the paragraph
        for run in para.runs:
            # Check if the run text is a keyword in the replacements dictionary
            if run.text in replacements:
                # Replace the keyword with the replacement and maintain the style
                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:
                                # Replace the keyword with the value
                                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
    
    # Specify the path of the output .pdf file
    pdf_output_path = os.path.splitext(pdf_input_path)[0] + '.pdf'
    
    # Convert the .docx file to .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)
    '''
    write sql code to upload this dictionary to its specified rows
    '''
    project_describtion['Project_Serial_Number']=serialnumber
    #CreateApplication('LPG application General.docx',project_describtion,serialnumber)

    #trying threading to run conversion in another thread
    Application=threading.Thread(target=CreateApplication,args=('LPG application General.docx',project_describtion,serialnumber))
    Application.start()

    # get the execution time

    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库时显示的错误,当我使用docx2pdf库时显示的类似错误:

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库,请注意,我给了所有需要的权限word和pdf到defaultapplicationpool和iis_iusr:

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)
bkhjykvo

bkhjykvo1#

根据堆栈跟踪,您的库正在自动化Word(在您的情况下是从IIS)的文件转换操作:

File "C:\inetpub\wwwroot\flpgproj\CreateFiles.py", line 35, in convert_to_pdf
    word=comtypes.client.CreateObject('Word.Application')

Microsoft当前不建议也不支持从任何无人参与的非交互式客户端应用程序或组件(包括ASP、ASP.NET、DCOM和NT服务)自动执行Microsoft Office应用程序,因为在此环境中运行Office时,Office可能会表现出不稳定的行为和/或死锁。
如果要生成在服务器端上下文中运行的解决方案,则应尝试使用对于无人参与的执行来说是安全的组件。或者,应尝试找到至少允许部分代码在客户端运行的替代方案。如果从服务器端解决方案使用Office应用程序,则该应用程序将缺少成功运行所需的许多功能。此外,您将冒整个解决方案稳定性的风险。请在Considerations for server-side Automation of Office文章中阅读更多相关内容。
如果您只处理Open XML文档,您可以考虑使用Open XML SDK,请参阅Welcome to the Open XML SDK 2.5 for Office了解更多信息。即使SDK不提供任何将文档转换为PDF文件格式的功能,您也可以找到构建在Open XML SDK之上的解决方案(开源库),它允许使用PDF文件格式导出/保存文档。
您也可以搜索系统上未安装Word的第三方组件/库进行文件转换(专为服务器端执行而设计)。

相关问题