COM problem when i run my flask code on IIS when using docx to pdf conversion

312 Views Asked by At

I have a flask app that contains a function to create a docx document then converts it to pdf, when i run the code on my local machine everything works fine and the pdf document is created but when i host the app on IIS on deployment machine with fastcgi module, it works fine and creates the docx document but doesn't create the pdf document due to an error, here is the function that creates docx document and converts to pdf using docx2pdf library:

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)

And here is how I call it from 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')})

and here is the error that shows up when i tried comtypes.client libreary, a similer error shows up when i use docx2pdf library:

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

and here is the exact same error that shows up when i use docx2pdf library, please note that i gave all required permissions to word and pdf to defaultapplicationpool and to 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)
1

There are 1 best solutions below

0
On

According to the stack-trace your libraries are automating Word (from IIS in your case) for the file conversion operations:

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

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

If you are dealing with open XML documents only you may consider using the Open XML SDK instead, see Welcome to the Open XML SDK 2.5 for Office for more information. Even if SDK doesn't provide anything for converting documents to the PDF file format, you may find solutions (open-source libraries) built on top of Open XML SDK that allows exporting/saving documents using the PDF file format.

Also you may search for third-party components/libraries that don't Word installed on the system for the file conversion (designed for the server-side execution).