How to convert any Document into PDF in Python

Our mission today is simple: set up a feature that will take in an Office document (XLSX, PPTX, DOCX, etc) or image and convert that file into a PDF. While you would usually be correct in thinking that this is a difficult task, I am here to show you a different and substantially easier way.

We start with our client’s installation:

pip install cloudmersive-convert-api-client

And following that we can proceed to call convert_document_autodetect_to_pdf, which is demonstrated right here:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.ConvertDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Convert Document to PDFapi_response = api_instance.convert_document_autodetect_to_pdf(input_file)pprint(api_response)except ApiException as e:print("Exception when calling ConvertDocumentApi->convert_document_autodetect_to_pdf: %s\n" % e)

The only thing that’s left to do is input your desired file and run it, returning you the PDF!

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store