Tornado - Create a PDF via Proxy using Java with JSON Data

This example shows how to generate a PDF from a DOCX template via a proxy server using Java.  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 to install and run Tornado.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * This sample code shows a render of the "WelcomeTemplate.docx" template using JSON format
 * instruction and data.
 *
 * There are several constants at the top of this file which you can modify to suit your test. You
 * need to set:
 *
 * If you would like to render via a web proxy, see the PROXY_* settings below to enable it.
 * 
 * Copyright Docmosis 2012
 */
public class JavaProxyJSONExample 
{

	private static final String DWS_RENDER_URL = "http://localhost:8080/api/render";

	// Set your access key here if you set your access key in Tornado configuration
	private static final String ACCESS_KEY = "";

	// The output format we want to produce (pdf, doc, odt and more exist)
	private static final String OUTPUT_FORMAT = "pdf";

	// the name of the file we are going to write the document to
	private static final String OUTPUT_FILE = "myWelcome." + OUTPUT_FORMAT;

	// Proxy settings if needed to reach the internet
	private static final String PROXY_HOST = "";
	private static final String PROXY_PORT = "";
	private static final String PROXY_USER = "";
	private static final String PROXY_PASSWD = "";

	/*
	 * Get a connection to the Docmosis render service
	 */
	private static HttpURLConnection getConnection() throws MalformedURLException, IOException {

		HttpURLConnection conn = (HttpURLConnection) new URL(DWS_RENDER_URL).openConnection();

		// PROXY Setup
		// if you have a proxy, set the values here to make sure you can reach the internet
		if (!"".equals(PROXY_HOST)) {
			System.setProperty("proxyHost", PROXY_HOST);
			System.setProperty("proxyPort", PROXY_PORT);
			System.setProperty("proxySet", "true");

			if (!"".equals(PROXY_USER)) {
				// set username and password for PROXY access
				String auth = Base64Helper.toBase64((PROXY_USER + ":" + PROXY_PASSWD).getBytes());
				conn.setRequestProperty("Proxy-Authorization", auth);
			}

			System.out.println("connecting [via proxy] to " + DWS_RENDER_URL);
		} else {
			System.out.println("Connecting [directly] to " + DWS_RENDER_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/json; charset=utf-8");

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

		return conn;
	}

	/*
	 * Build the request in JSON format. You can do it in XML if you prefer (code not shown here).
	 */
	private static String buildRequest() {
		// the name of the template in Tornado
		String templateName = "WelcomeTemplate.docx";

		StringBuilder sb = new StringBuilder();

		// Start building the instruction
		sb.append("{\n");
		sb.append("\"accessKey\":\"").append(ACCESS_KEY).append("\",\n");
		sb.append("\"templateName\":\"").append(templateName).append("\",\n");
		sb.append("\"outputName\":\"").append(OUTPUT_FILE).append("\",\n");

		// now add the data specifically for this template
		sb.append("\"data\":{\n");
		sb.append("\"date\":\"").append(new Date()).append("\",\n");
		sb.append("\"message\":\"This Tornado Document Engine is working great!\",\n");
		sb.append("}\n");

		// end the entire instruction
		sb.append("}\n");

		return sb.toString();

	}

	/*
	 * Save the given Input stream to a file
	 */
	private static void saveToFile(InputStream content) throws IOException {
		byte[] buff = new byte[1000];
		int bytesRead = 0;

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

		System.out.println("Created file:" + file.getAbsolutePath());
	}

	/*
	 * Something went wrong in the call to the service, tell the user about it
	 */
	private static void processError(HttpURLConnection conn, int status)
			throws IOException {
		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;

	}

	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException {

		HttpURLConnection conn = null;
		try {
			conn = getConnection();
		} catch (ConnectException e) {
			// can't make the connection
			System.err.println("Unable to connect to Docmosis:" + e.getMessage());
			System.err.println("If you have a proxy, configure proxy settings at the top of this example.");
			System.exit(2);
		}

		try {
			String renderRequest = buildRequest();

			System.out.println("Sending request:" + renderRequest);

			// write data using UTF-8 encoding so that most character sets are
			// available
			OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			os.write(renderRequest);
			os.flush();

			int status = conn.getResponseCode();

			if (status == 200) {
				// successful render,
				// save our document to a file
				saveToFile(conn.getInputStream());
			} else {
				// something went wrong - tell the user
				processError(conn, status);
			}

		} finally {
			conn.disconnect();
		}

	}

	/**
	 * A helper for dealing with Base64 encoding.  This is only needed if you are
	 * using a proxy to reach the internet and must authenticate with the proxy.
	 */
	private static class Base64Helper
	{
		private static final char[] B64_DIGIT = { 'A', 'B', 'C', 'D', 'E', 'F',
			'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
			'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
			't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', '+', '-' };

		public static String toBase64(byte[] data) {
			int i = 0;
			int chunks = data.length / 3;
			StringBuilder sb = new StringBuilder(chunks * 4 + 2);
			for (int count = 0; count < chunks; count++, i += 3) {
				int buffer = ((data[i] & 0xFF) << 16) | ((data[i + 1] & 0xFF) << 8)
						| (data[i + 2] & 0xFF);
				sb.append(B64_DIGIT[(buffer & 0xFC0000) >> 18]);
				sb.append(B64_DIGIT[(buffer & 0x03F000) >> 12]);
				sb.append(B64_DIGIT[(buffer & 0x000FC0) >> 6]);
				sb.append(B64_DIGIT[(buffer & 0x00003F)]);
			}
			// padding
			int buffer;
			switch (data.length - i) {
			case 2:
				buffer = ((data[i] & 0xFF) << 16) | ((data[i + 1] & 0xFF) << 8);
				sb.append(B64_DIGIT[(buffer & 0xFC0000) >> 18]);
				sb.append(B64_DIGIT[(buffer & 0x03F000) >> 12]);
				sb.append(B64_DIGIT[(buffer & 0x000FC0) >> 6]);
				sb.append('=');
				break;
			case 1:
				buffer = ((data[i] & 0xFF) << 16);
				sb.append(B64_DIGIT[(buffer & 0xFC0000) >> 18]);
				sb.append(B64_DIGIT[(buffer & 0x03F000) >> 12]);
				sb.append("==");
				break;
			}
			return sb.toString();
		}
	}
}

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.