Tornado Code Samples

This page contains a collection of code samples for using Docmosis Tornado.

You'll need download and install Tornado then run the samples to connect to it.

 

C# Render

cURL Render using the command line

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 Tornado 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.
 * 
 * This is applicable to Docmosis Tornado version 2.6 onwards. 
 * 
 * Copyright Docmosis 2017
 */
public class GetTemplateSampleDataExample 
{

	private static final String URL = "http://localhost:8080/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 = "";

		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 = "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 Tornado 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 
{

	private static final String URL = "http://localhost:8080/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 = "";

		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 = "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.
 * 
 * The "renderForm" end-point is supported from Tornado version 2.5 
 * 
 * Copyright Docmosis 2017
 */
public class JavaRenderURLEncoded 
{

	private static final String URL = "http://localhost:8080/rs/renderForm";

	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException 
	{
		// Set your access Key if you configure it in Tornado
		final String accessKey = "";
		final String outputFileName = "result.pdf";
		
		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 = "WelcomeTemplate.doc";
			
			String date = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
			String message = "Hello from my Java form post";
			
			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")
				+ "&message=" + URLEncoder.encode(message, "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

PHP Render Example



 
<?php

     # This sample PHP code calls the local Tornado server to render the default "WelcomeTemplate.doc" into a PDF file.

     $accessKey = '';
     $templateName = 'WelcomeTemplate.doc';
     $outputName = 'output.pdf';

     $data = '{"date":"20/Jan/2015","message":"This Tornado Document Engine is working great!"}';

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


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

     $ch = curl_init('http://localhost:8080/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);

     $responseData = curl_exec($ch);
     $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";
     }

?>
 

Python Render Example

Ruby Render