Consume A SOAP Web Service Using Python

Python is one of the most popular modern programming languages, as it’s a straightforward language with a basic syntax, yet it’s very powerful and very flexible.

In this post, we’ll consume Muhimbi’s Convert SOAP Web Service using Python and convert a File to PDF.

Before we begin, please make sure the following prerequisites are in place:

  • Install and configure a Windows Server or VM with a public facing IP address.
  • Download the fully functional free trial of The Muhimbi PDF Converter Services here.
  • Please make sure The Muhimbi PDF Converter Services is installed exactly as described in chapter 2 of the Administration Guide. Please follow that guide to the letter and make sure you pay particular good attention to the section about ‘dependencies’. The Administration Guide is included in the download and available on-line here.
  • Install and Configure Python with reference to this article.
  • Install the Requests and Base64 python libraries.

Please find our Final Python script below:

#We will need the library to convert file content to base64 
import base64

#We will need  the os library to read and write a files
import os

# Use the requests library to simplify making a REST API call from Python 
import requests

#We will need the os library to interact with paths 
from pathlib import Path

#We will need the library to parse with XML 
from xml.etree import ElementTree
 
UserInput = input('Please Enter the Path of the File you want to Convert:')
 
if os.path.exists(UserInput):
    originalpath = UserInput.replace('/','//')
    path = os.path.abspath(originalpath)
    basefilename = os.path.basename(originalpath)
 
    #Get base64 Content
    data = open(path, 'rb').read()
    base = base64.b64encode(data)
    sourceFile1= str(base)
    souce_file_conent = base.decode('utf-8')
    extension = os.path.splitext(basefilename)[1][1:]
	
	#URL for the Muhimbi Conversion Server
    address = 'http://<your_server_name>:41734/Muhimbi.DocumentConverter.WebService/?Wsdl'
	
	#We need to specify the SOAPAction and the content type
    #in the HTTP header. 
    headers = {'SOAPAction': 'http://services.muhimbi.com/2009/10/06/DocumentConverterService/Convert', 'Content-Type':'text/xml'}
	
	#We need to specify the
    body = """<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:ns="http://services.muhimbi.com/2009/10/06" 
    xmlns:ns1="http://types.muhimbi.com/2009/10/06" 
    xmlns:ns2="http://types.muhimbi.com/2014/02/06"
    xmlns:ns3="http://types.muhimbi.com/2015/04/13" 
    xmlns:ns4="http://types.muhimbi.com/2010/05/17" 
    xmlns:ns5="http://types.muhimbi.com/2013/08/01" 
    xmlns:ns6="http://types.muhimbi.com/2013/01/14">
    <soapenv:Header/>
    <soapenv:Body>
      <ns:Convert>         
         <ns:sourceFile>"""+souce_file_conent+"""</ns:sourceFile>
         <ns:openOptions>            
            <ns1:FileExtension>"""+extension+"""</ns1:FileExtension>            
            <ns1:OriginalFileName>"""+basefilename+"""</ns1:OriginalFileName>            
         </ns:openOptions>         
         <ns:conversionSettings>            
            <ns1:Format>PDF</ns1:Format>           
            <ns1:Fidelity>Full</ns1:Fidelity>           
            <ns1:ConverterSpecificSettings/>           
            <ns1:OutputFormatSpecificSettings/>            
         </ns:conversionSettings>
      </ns:Convert>
    </soapenv:Body>
    </soapenv:Envelope>"""
 
    try:
		# We use HTTP POST to call this function
        response = requests.post(address, headers=headers,data=body)
        dom = ElementTree.fromstring(response.content)
        namespaces = {
            'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
            'a': 'http://services.muhimbi.com/2009/10/06',
        }
		#Parsing the XML to get filecontent
        names = dom.findall(
        './soap:Body'
        '/a:ConvertResponse'
        '/a:ConvertResult',
        namespaces,
        )
        for name in names:
            processed_file_content  = name.text
            filecontent = processed_file_content.encode()
            #print(processed_file_content)
            with open(basefilename+'_Processed.pdf', 'wb') as fh:
                fh.write(base64.b64decode(filecontent))
                fh.close
    except:
        print('The Error is:' +response)
else:
    print('Invalid Path')


Run the Python script from your command prompt and provide the ‘Path of the document’ that needs to be converted. Sample commands to run the script and the expected output are shown below:

Code Execution on Window
Code Execution on Ubuntu

You should find a PDF document in the Folder which holds the python script. In the next blog we will invoke a REST API to Convert Files to PDF.

Subscribe to this blog for the latest updates about SharePoint Online, Microsoft Flow, Power Apps and document conversion and manipulation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s