Cloud - Create a PDF using Java with XML Data via API

This example shows how to generate a PDF from a DOCX template 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 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.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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 "samples/WelcomeTemplate.docx" template using XML format
 * instruction and data.
 *
 * You need to set your access key before this example will run.  This key is your unique access to 
 * the Docmosis services (keep it safe). You can see your access key in your Account Settings in the 
 * Cloud area Docmosis web site.
 *
 * If you have troubles connecting, it may be because you have a proxy server you need to
 * configure. See the more complete example which provides proxy settings.
 * 
 * Copyright Docmosis 2019
 */
public class JavaBasicXMLExample 
{
	// Set your region here.
	// End-point in the USA
	private static final String DWS_RENDER_URL = "https://us1.dws4.docmosis.com/api/render";
	// End-point in the EU
	//private static final String DWS_RENDER_URL = "https://eu1.dws4.docmosis.com/api/render";
	// End-point in AUS
	//private static final String DWS_RENDER_URL = "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.
	private static final String ACCESS_KEY = "XXX";
	
	

	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException 
	{
		if ("XXX".equals(ACCESS_KEY)) {
			System.err.println("Please set your private access key from your Docmosis cloud account.");
			System.exit(1);
		}

		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(DWS_RENDER_URL).openConnection();
			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/xml; charset=utf-8");

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

			final String outputFileName = "myWelcome.pdf";

			// build request
			String templateName = "samples/WelcomeTemplate.docx";
			StringBuffer sb = new StringBuffer();

			// Start building the instruction
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			sb.append("<render \n");
			sb.append("accessKey=\"").append(ACCESS_KEY).append("\" ");
			sb.append("templateName=\"").append(templateName).append("\" ");
			sb.append("outputName=\"").append(outputFileName).append("\">\n");

			// now add the data specifically for this template
			sb.append("<data\n");
			sb.append(" title=\"Welcome to Docmosis in the Cloud\">\n");
			String[] messages = { "This cloud experience is better than I thought.",
					      "The sun is shining", "Right, now back to work." };
			for (int i = 0; i < messages.length; i++) {
				sb.append("<messages msg=\"").append(messages[i]).append("\"/>\n");
			}
			sb.append("</data>\n");
			sb.append("</render>\n");

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

			// send the instruction in UTF-8 encoding so that most character sets are available
			OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			os.write(sb.toString());
			os.flush();
			
			int status = conn.getResponseCode();
			if (status == 200) {
				// successful render,
				// save our document to a file
				byte[] buff = new byte[1000];
				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 the docmosis cloud:" + e.getMessage());
			System.err.println("If you have a proxy, you will need the Proxy aware example code.");
			System.exit(2);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}

	}
}

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.