Cloud - Create a PDF using Python via API

This example shows how to generate a PDF from a DOCX template using Python.  It calls the Docmosis REST API to merge the data with the template and stream the result back.

The sample code includes the instructions to get started. You will need a Free Trial and then plug your Docmosis Cloud access key into the code below, then run.

Note: This code sample is written to specifically work with DWS4.

# This example shows how to use Python to call the Docmosis Cloud service to render a PDF from the default WelcomeTemplate.docx template.

import requests
import json
import datetime

# Set your region url here.
# End-point in the USA
DWSrenderURL = 'https://us1.dws4.docmosis.com/api/render'
# End-point in the EU
#DWSrenderURL = 'https://eu1.dws4.docmosis.com/api/render'
# End-point in AUS
#DWSrenderURL = 'https://au1.dws4.docmosis.com/api/render'

# Set your access key here. This is visible in your cloud account in the Docmosis Web Site.
# It is your key to accessing your service - keep it private and safe.
accessKey='XXX'

if accessKey=='XXX':
  print("Please set your access key")
  exit()

dataStr = '{"title":"Hello from PYTHON", "messages":[{"msg":"This cloud experience is better than I thought."}, {"msg":"The sun is shining."}, {"msg":"Right, now back to work."}]}'
payload = '{"accessKey": "' + accessKey + '", "templateName":"samples/WelcomeTemplate.docx", "outputName":"myWelcome.pdf", "data":' + dataStr + '}'

headers = {'content-type': 'application/json'}
r = requests.post(DWSrenderURL, data=payload, headers = headers)

if r.status_code == requests.codes.ok:

  with open('myWelcome.pdf', 'wb') as fd:
    for chunk in r.iter_content(4096):
        fd.write(chunk)
  print("Saved to myWelcome.pdf");
else:
  print("Failed");
  print(r.text)
 

Feedback

Invalid Input

Sorry, this field will only accept letters and numbers, and not special characters, to limit spam. Please also consider contacting support@docmosis.com if you need help with this article.

Sorry, this field will only accept letters and numbers, and not special characters, to limit spam.

Invalid Input

API Overview

Docmosis offers a high-performance, template-based PDF generation API. Suitable for use with custom software applications built using Java, C#/.Net, Python, Ruby and more. See a side-by-side comparison of the API for our SaaS and self-hosted products.