Cloud Code Samples

This page contains a collection of code samples that use the Docmosis Cloud service.

You will also need to create a Cloud account and then run the samples to connect to it.

 

C# Render

cURL Render using the command line

Elixir Render to PDF



This example shows how to generate a PDF from a DOC template using Elixir.  It calls the Docomsis 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.

Java Get Template Sample Data






import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * This sample code shows a call to Docmosis to get sample data suitable to populate
 * the  "WelcomeTemplate.doc" template.  
 *  
 * The response is a JSON structure and it contains a sub-structure of data matching
 * the template.
 * 
 * Copyright Docmosis 2017
 */
public class GetTemplateSampleDataExample 
{

	// End-point in the USA
	private static final String URL = "https://dws2.docmosis.com/services/rs/getSampleData";
	// End-point in the EU
	//private static final String URL = "https://eu-west.dws2.docmosis.com/services/rs/getSampleData";

	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException 
	{
		// Set your access Key if you configure it in Tornado
		String accessKey = "";

		if (accessKey.isEmpty()) {
			System.err.println("You must set the access key");
			System.exit(1);
		}

		HttpURLConnection conn = null;
		DataOutputStream os = null;
		try {
			conn = (HttpURLConnection) new URL(URL).openConnection();
			System.out.println("Connecting [directly] to " + URL);

			// set connection parameters
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// this example uses JSON format
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			conn.connect();
			System.out.println("Connected");

			// build request
			final String templateName = "samples/WelcomeTemplate.doc";
			
			final String params = "accessKey=" + accessKey + "&templateName=" + templateName;
			System.out.println("Sending request:" + params);
			final byte[] postData = params.getBytes( Charset.forName("UTF-8") );
			
			// send the parameters
			os = new DataOutputStream(conn.getOutputStream());
			os.write(postData);
			os.flush();
			
			// get the response
			int status = conn.getResponseCode();
			if (status == 200) {
				// successful call, extract the response
				
				BufferedReader br = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				StringBuffer sb = new StringBuffer();
				String msg;
				while ((msg = br.readLine()) != null) {
					sb.append(msg);
				}
				System.out.println("response:" + sb.toString());
				
				// add code here to process the response as JSON and 
				// in particular the "templateSampleData" field.
				
				br = null;
			} else {
				// something went wrong - tell the user
				System.err.println("Our call failed: status = " + status);
				System.err.println("message:" + conn.getResponseMessage());
				BufferedReader errorReader = new BufferedReader(
						new InputStreamReader(conn.getErrorStream()));
				String msg;
				while ((msg = errorReader.readLine()) != null) {
					System.err.println(msg);
				}
				errorReader = null;
			}
			
		} catch (ConnectException e) {
			// can't make the connection
			System.err.println("Unable to connect to Docmosis:" + e.getMessage());
			System.exit(2);
		} finally {
			if (os != null) {
				os.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}

	}
}

Java Get Template Structure






import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * This sample code shows a call to Docmosis to get the structure of the "WelcomeTemplate.doc" template 
 * The response is a JSON structure describing the fields, images and sections of the template.
 * 
 * Copyright Docmosis 2017
 */
public class GetTemplateStructureExample 
{

	// End-point in the USA
	private static final String URL = "https://dws2.docmosis.com/services/rs/getTemplateStructure";
	// End-point in the EU
	//private static final String URL = "https://eu-west.dws2.docmosis.com/services/rs/getTemplateStructure";

	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException 
	{
		// Set your access Key if you configure it in Tornado
		String accessKey = "";
		
		if (accessKey.isEmpty()) {
			System.err.println("You must set the access key");
			System.exit(1);
		}

		HttpURLConnection conn = null;
		DataOutputStream os = null;
		try {
			conn = (HttpURLConnection) new URL(URL).openConnection();
			System.out.println("Connecting [directly] to " + URL);

			// set connection parameters
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// this example uses JSON format
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			conn.connect();
			System.out.println("Connected");

			// build request
			final String templateName = "samples/WelcomeTemplate.doc";
			
			final String params = "accessKey=" + accessKey + "&templateName=" + templateName;
			System.out.println("Sending request:" + params);
			final byte[] postData = params.getBytes( Charset.forName("UTF-8") );
			
			// send the parameters
			os = new DataOutputStream(conn.getOutputStream());
			os.write(postData);
			os.flush();
			
			// get the response
			int status = conn.getResponseCode();
			if (status == 200) {
				// successful call, extract the response
				
				BufferedReader br = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				StringBuffer sb = new StringBuffer();
				String msg;
				while ((msg = br.readLine()) != null) {
					sb.append(msg);
				}
				System.out.println("response:" + sb.toString());
				
				// add code here to process the response as JSON and 
				// in particular the "templateStructure" field.
				
				br = null;
			} else {
				// something went wrong - tell the user
				System.err.println("Our call failed: status = " + status);
				System.err.println("message:" + conn.getResponseMessage());
				BufferedReader errorReader = new BufferedReader(
						new InputStreamReader(conn.getErrorStream()));
				String msg;
				while ((msg = errorReader.readLine()) != null) {
					System.err.println(msg);
				}
				errorReader = null;
			}
			
		} catch (ConnectException e) {
			// can't make the connection
			System.err.println("Unable to connect to Docmosis:" + e.getMessage());
			System.exit(2);
		} finally {
			if (os != null) {
				os.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}

	}
}

Java Render using JSON

Java Render using URL Encoding






import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This sample code shows how to use Docmosis to render a url-encoded form.
 * 
 * Copyright Docmosis 2017
 */
public class JavaRenderURLEncoded 
{

	// End-point in the USA
	private static final String URL = "https://dws2.docmosis.com/services/rs/renderForm";
	// End-point in the EU
	//private static final String URL = "https://eu-west.dws2.docmosis.com/services/rs/renderForm";
	
	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException 
	{
		final String accessKey = "";
		final String outputFileName = "result.pdf";
		
		if (accessKey.isEmpty()) {
			System.err.println("You must set the access key");
			System.exit(1);
		}
		
		HttpURLConnection conn = null;
		DataOutputStream os = null;
		try {
			conn = (HttpURLConnection) new URL(URL).openConnection();
			System.out.println("Connecting [directly] to " + URL);

			// set connection parameters
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// use a url-encoded form.
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			conn.connect();
			System.out.println("Connected");

			// build request
			final String templateName = "samples/WelcomeTemplate.doc";
			
			String date = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
			String title = "Hello Cloud my Java form post";
			String message1 = "This is message 1";
			String message2 = "I like writing messages";
			String message3 = "And also posting them into a document";
			
			final String params = 
				// docmosis parameters
				"accessKey=" + URLEncoder.encode(accessKey, "UTF-8") 
				+ "&templateName=" + URLEncoder.encode(templateName, "UTF-8") 
				+ "&outputName=" + URLEncoder.encode(outputFileName, "UTF-8")
				// data parameters
				+ "&date=" + URLEncoder.encode(date, "UTF-8")
				+ "&title=" + URLEncoder.encode(title, "UTF-8")
				// we use an "indexed string" to supply an array of "messages", each with a "msg"
				+ "&messages.0.msg=" + URLEncoder.encode(message1, "UTF-8")
				+ "&messages.1.msg=" + URLEncoder.encode(message2, "UTF-8")
				+ "&messages.2.msg=" + URLEncoder.encode(message3, "UTF-8")
				;
			System.out.println("Sending request:" + params);
			final byte[] postData = params.getBytes( Charset.forName("UTF-8") );
			
			// send the parameters
			os = new DataOutputStream(conn.getOutputStream());
			os.write(postData);
			os.flush();
			
			// get the response
			int status = conn.getResponseCode();
			if (status == 200) {
				// successful call, extract the response

				// successful render,
				// save our document to a file
				byte[] buff = new byte[4096];
				int bytesRead = 0;

				File file = new File(outputFileName);
				FileOutputStream fos = new FileOutputStream(file);
				try {
					while ((bytesRead = conn.getInputStream().read(buff, 0, buff.length)) != -1) {
						fos.write(buff, 0, bytesRead);
					}
				} finally {
					fos.close();
				}

				System.out.println("Created file:" + file.getAbsolutePath());
			} else {
				// something went wrong - tell the user
				System.err.println("Our call failed: status = " + status);
				System.err.println("message:" + conn.getResponseMessage());
				BufferedReader errorReader = new BufferedReader(
						new InputStreamReader(conn.getErrorStream()));
				String msg;
				while ((msg = errorReader.readLine()) != null) {
					System.err.println(msg);
				}
				errorReader = null;
			}
			
		} catch (ConnectException e) {
			// can't make the connection
			System.err.println("Unable to connect to Docmosis:" + e.getMessage());
			System.exit(2);
		} finally {
			if (os != null) {
				os.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}

	}
}

Java Render using XML

Java Render via Proxy using JSON

Java Render via Proxy using XML

Java Upload Template Example

Node.js Render Example



// This Node.js example calls the Docmosis web service to create a PDF document
// from the default template (samples/WelcomeTemplate.doc).
// To run:
//  1) plug your Docmosis access key into the accessKey variable
//
// Copyright Docmosis 2017
//

const https = require("https");
const querystring = require("querystring");
const fs = require("fs");

// RESTful service host
const hostname = "dws2.docmosis.com";

// Your account key
const accessKey = "XXXXX";

// make sure the access key above has been set
if (accessKey == "XXXXX") {
    console.log("Please set your access key in this example");
    process.exit();
}

// The template to use
// NOTE that it has to be defined in your account with the same name specified here
const template = "samples/WelcomeTemplate.doc"; // Change with your actual template name

// The output file name
const output = "myWelcome.pdf";

// The data to use for generating the document
const data = {
    date:new Date().toDateString(),
    title:"Welcome to Docmosis in the Cloud",
    messages:[
        {"msg":"This cloud experience is better than I thought."},
        {"msg":"It's so easy to create documents!"},
        {"msg":"Right, now back to work."}
    ]
}

const postData = querystring.stringify({
    "accessKey":accessKey,
    "templateName":template,
    "outputName":output,
    "data":JSON.stringify(data)
});

const options = {
    hostname: hostname,
    port: 443,
    path: "/services/rs/render",
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": Buffer.byteLength(postData)
    }
};

const req = https.request(options, (res) => {
    switch (res.statusCode) {
    case 200:
        var file = fs.createWriteStream(output);

        // feed response into file
        res.pipe(file);
        file.on("finish", () => {
            file.close();
            console.log(output, "created");
        });
        break;
    default:
        // 4XX errors - client errors - something needs to be corrected in the request
        // 5XX errors - server side errors - possibly worth a retry

        // show error response (details)
        console.log("Error response:", res.statusCode, res.statusMessage);
        var response = "";
        res.on("data", (data) => {
            response += data;
        });
        res.on("end", () => {
            console.log(response);
        });
    }
});

req.on("error", (e) => {
    console.error("Request error:", JSON.stringify(e, null, 4));
});

// write data to request body
req.write(postData);
req.end();

PHP Render Example



<?php

     # This sample PHP code calls the Docmosis cloud to render the default "samples/WelcomeTemplate.doc" into a PDF file.

     $accessKey = 'XXXX';


     if ($accessKey == 'XXXX') {
        echo "Please set your access key\n";
        exit(1);
     }

     $templateName = 'samples/WelcomeTemplate.doc';
     $outputName = 'output.pdf';

     $data = '{"date":"20/Jan/2015",
               "title":"Welcome to Docmosis in the Cloud",
               "messages":
               [{"msg":"This cloud experience is better than I thought."},
                {"msg":"The sun is shining."},
                {"msg":"Right, now back to work."}]
              }';

     $request = array(
       "accessKey" => $accessKey,
       "templateName" => "$templateName",
       "outputName" => "$outputName",
       "data" => "$data"
     );


     $requestHeaders = array('Content-Type' => 'multipart/form-data');

     $ch = curl_init('https://dws2.docmosis.com/services/rs/render');

     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

     $responseData = curl_exec($ch);

     if ( $responseData != false) {

       $headers = curl_getinfo($ch);
       curl_close($ch);

       if ($headers['http_code'] == '200')  {

         // success!!
         // write the file out (since we didn't say where to send the
         // result, Docmosis sent us the result)

         $tempDirName = ".";
         $tempFileName = realpath($tempDirName) . "/" . $outputName;

         $renderedFile = file_put_contents($tempFileName, $responseData);

         echo "File saved to $tempFileName\n";

       } else {
         // failed - check error and result message
         echo "Failed:" . $responseData . "\n";
       }

     } else {

         echo "curlexec failed.\n\nDocmosis Cloud must be used via HTTPS.\n\nCheck your CA certificates, or try un-commenting CURLOPT_SSL_VERIFYPEER line (for troubleshooting only)";

     }


?>
 

Python Delete Template Example

Python Render Example

Python Upload Template Example

Ruby Render

Ruby Upload