### Java Proxy XML Example Setup
Source: https://resources.docmosis.com/CodeSamples/Tornado/JavaProxyXMLExample.java
This section covers the initial setup for the Java example, including constants for the render URL, access key, output format, and file names. It also includes proxy configuration details.
```Java
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 XML format
* instruction and data.
*
* If you would like to render via a web proxy, see the PROXY_* settings below to enable it.
*
* Copyright Docmosis 2012
*/
public class JavaProxyXMLExample
{
private static final String DWS_RENDER_URL = "http://localhost:8080/api/render";
// set the access key if you configure it in Tornado
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 XML format
conn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
conn.connect();
System.out.println("Connected");
return conn;
}
/*
* Build the request in XML format. You can do it in JSON if you prefer (code not shown here).
*/
private static String buildRequest() {
// the name of the template in Tornado to use
String templateName = "WelcomeTemplate.docx";
StringBuilder sb = new StringBuilder();
// Start building the instruction
sb.append("");
sb.append("
");
// now add the data specifically for this template
sb.append("
sb.append("
");
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 {
```
--------------------------------
### Docmosis-Java: Create PDF from Template
Source: https://resources.docmosis.com/search?category_id=8&isc=1&issearch=1&ordering=zelevance
This example shows the simplest way to create a PDF document using Docmosis-Java with a DOCX template. It includes instructions for getting started.
```java
public class SimpleRender {
public static void main(String[] args) {
// TODO Auto-generated method stub
// DocmosisDocOptions options = new DocmosisDocOptions();
// options.setOutputName("SimpleRender.pdf");
// Docmosis.renderTemplate("WelcomeTemplate.docx", options);
}
}
```
--------------------------------
### Main Execution Method for Docmosis Example
Source: https://resources.docmosis.com/CodeSamples/Tornado/JavaProxyJSONExample.java
The main entry point for the example. It attempts to establish a connection to the Docmosis service and catches connection errors.
```Java
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());
```
--------------------------------
### C# Example: Render DOCX Template to PDF via API
Source: https://resources.docmosis.com/code-samples/tornado-create-a-pdf-using-c-via-api
This C# code snippet shows how to render a DOCX template to a PDF using the Docmosis REST API. It includes setup for local or proxied API calls and handles the response, saving the output to a file. Ensure you have a Docmosis trial installed to run this example.
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace Docmosis
{
///
/// This sample code shows a render of the "WelcomeTemplate.docx" template using JSON format
/// instruction and data via the local Tornado server (localhost:8080).
///
/// If you wish to test via a web proxy server, see the PROXY_* settings below to enable it.
///
///
/// Copyright Docmosis 2015
///
class CSRenderExample
{
private static string DWS_RENDER_URL = "http://localhost:8080/api/render";
// Set your access key here. The access key is only required if configured in Tornado.
private const string ACCESS_KEY = "";
// The output format we want to produce (pdf, doc, odt and more exist)
private const string OUTPUT_FORMAT = "pdf";
// the name of the template (stored in Tornado) to use
private const string TEMPLATE = "WelcomeTemplate.docx";
// the name of the file we are going to write the document to
private const string OUTPUT_FILE = "myWelcome." + OUTPUT_FORMAT;
// Proxy settings if needed to reach the internet
private const string PROXY_HOST = "";
private const string PROXY_PORT = "";
private const string PROXY_USER = "";
private const string PROXY_PASSWD = "";
static void Main(string[] args)
{
HttpWebResponse response;
try
{
response = sendRequest();
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
saveToFile(response.GetResponseStream());
}
else
{
processError(response);
}
}
finally
{
response.Close();
}
}
catch (WebException e)
{
Console.WriteLine("ERROR:" + e.Message);
using (WebResponse webResponse = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)webResponse;
processError(httpResponse);
}
}
catch (Exception e)
{
Console.Error.WriteLine("Unable to connect to Docmosis: " + e.Message);
Console.Error.WriteLine(e.StackTrace);
Console.Error.WriteLine("If you have a proxy, configure proxy settings at the top of this example.");
Console.ReadKey();
System.Environment.Exit(2);
}
Console.Out.WriteLine("Press any key");
Console.ReadKey();
}
///
/// Sends the request to the server and returns the response.
///
///
/// the response returned by the server
///
static HttpWebResponse sendRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(DWS_RENDER_URL);
if (PROXY_HOST.Length != 0)
{
WebProxy proxy = new WebProxy(PROXY_HOST + ":" + PROXY_PORT, true);
if (PROXY_USER.Length != 0)
{
proxy.Credentials = new NetworkCredential(PROXY_USER, PROXY_PASSWD);
}
Console.WriteLine(proxy.Address);
request.Proxy = proxy;
}
string renderRequest = buildRequest();
Console.WriteLine("Sending request:" + renderRequest);
byte[] data = new UTF8Encoding().GetBytes(renderRequest);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
return (HttpWebResponse)request.GetResponse();
}
///
/// Build the request in JSON format. You can do it in XML if you prefer (code not shown here).
///
private static string buildRequest()
{
StringBuilder sb = new StringBuilder();
// Start building the instruction
sb.Append("{\n");
sb.Append("\"accessKey\":\"").Append(ACCESS_KEY).Append("\",\n");
sb.Append("\"templateName\":\"").Append(TEMPLATE).Append("\",\n");
```
--------------------------------
### Example Date Formatting
Source: https://resources.docmosis.com/template-tutorials/format-dates
This example demonstrates formatting a raw date '21-03-16' into a more readable format 'Monday - March 21, 2016' using the dateFormat function.
```Docmosis Template Language
dateFormat('21-03-16', 'EEEE - MMMM dd, yyyy', 'yy-MM-dd')
```
--------------------------------
### API Processing Location Example
Source: https://resources.docmosis.com/faq/cloud-processing-location
This example shows a Base URL that directs API operations to the EU region for processing. Ensure your templates and images are accessible in this region.
```text
https://**eu1**.dwsX.docmosis.com/api
```
--------------------------------
### Main Method for Docmosis Cloud Interaction
Source: https://resources.docmosis.com/CodeSamples/Cloud/DWS4/JavaProxyXMLExample.java
The main entry point for the example. It sets up the connection, builds the request, sends it to the Docmosis Cloud, and processes the response or errors. Ensure your ACCESS_KEY is set.
```Java
public static void main(String[] args) throws MalformedURLException,
IOException {
if ("XXX".equals(ACCESS_KEY)) {
System.err.println("Please set your private ACCESS_KEY at the top of this file from your Docmosis cloud account.");
System.exit(1);
}
HttpURLConnection conn = null;
try {
conn = getConnection();
} 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, 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();
}
}
```
--------------------------------
### Get Template Structure with Python
Source: https://resources.docmosis.com/code-samples/tornado-get-template-structure-using-python-via-api
This Python script calls the Docmosis REST API to fetch the structure of a specified template. It handles both direct requests and requests via a proxy server. Ensure you have a free trial of Tornado installed and running locally.
```python
# This sample code shows how to get the structure of the "WelcomeTemplate.docx" template in JSON format
# via the local Tornado server (localhost:8080).
# If you wish to test via a web proxy server, set useProxy to True and see the proxies settings below to enable it.
import requests
import json
import datetime
accessKey=''
templateName='WelcomeTemplate.docx'
useProxy = False
proxies = {'http': 'http://username:password@ip:port',
'https': 'http://username:password@ip:port'}
# Create request
payload = 'accessKey=' + accessKey + '&templateName=' + templateName
headers = {'content-type': 'application/x-www-form-urlencoded'}
# Make request
if useProxy:
r = requests.post("http://localhost:8080/api/getTemplateStructure", data=payload, headers=headers, proxies=proxies)
else:
r = requests.post("http://localhost:8080/api/getTemplateStructure", data=payload, headers=headers)
# Process response
if r.status_code == 200:
jsonResponse = r.json()
if 'templateStructure' in jsonResponse:
print(json.dumps(jsonResponse['templateStructure'], indent=4, sort_keys=True))
else:
print("Failed")
print(r.text)
```
--------------------------------
### Tornado: Create PDF using PHP
Source: https://resources.docmosis.com/search?category_id=8&isc=1&issearch=1&ordering=zelevance
This example demonstrates generating a PDF from a DOCX template using PHP by calling the Docmosis REST API. Ensure the API is accessible.
```php
'Docmosis',
'version' => 'Tornado'
);
$headers = array(
'Content-Type: application/json'
);
$ch = curl_init($url);
c_setopt($ch, CURLOPT_RETURNTRANSFER, true);
c_setopt($ch, CURLOPT_POST, true);
c_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
c_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
} else {
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
file_put_contents('output.pdf', $response);
echo "PDF generated successfully!";
} else {
echo "Error: " . curl_getinfo($ch, CURLINFO_HTTP_CODE) . "\n";
echo $response;
}
}
curl_close($ch);
?>
```
--------------------------------
### Docmosis Java Configuration Example
Source: https://resources.docmosis.com/code-samples/docmosis-java-configure-using-properties-files
This Java code initializes the Docmosis system using settings from 'docmosis.properties', creates a PDF from a DOCX template with dynamic data, and then shuts down the system. Ensure 'docmosis.properties' and 'WelcomeTemplate.docx' are accessible.
```java
import java.io.File;
import com.docmosis.SystemManager;
import com.docmosis.document.DocumentProcessor;
import com.docmosis.template.population.DataProviderBuilder;
/**
* A simple example showing Docmosis creating a PDF with dynamic data from a DOCX
* template.
*/
public class DocmosisConfigFiles {
public static void main(String[] args) {
// Use the DataProviderBuilder to build the data provider from Strings
DataProviderBuilder dpb = new DataProviderBuilder();
dpb.add("date", "12 Jun 2016");
dpb.add("message", "This Docmosis Document Engine is working!");
try {
// Initialize the system using the "docmosis.properties" file
SystemManager.initialise();
File templateFile = new File("WelcomeTemplate.docx");
File outputFile = new File("newDocument.pdf");
if (!templateFile.canRead()) {
System.err.println("\nCannot find '" + templateFile + "' in: " + new File("").getCanonicalPath());
} else {
// Create the document
DocumentProcessor.renderDoc(templateFile, outputFile, dpb.getDataProvider());
System.out.println("\nCreated: " + outputFile.getCanonicalPath());
}
} catch (Exception e) {
System.err.println("\nPlease check the following: " + e.getMessage());
} finally {
// Shutdown the system
SystemManager.release();
}
}
}
```
--------------------------------
### Docmosis API JSON Payload Example
Source: https://resources.docmosis.com/integrations/generate-a-document-from-bubble-part-2
This is an example of the JSON structure expected by the Docmosis API for generating a document, including nested items.
```json
{
"invoiceNo": "00000135",
"invoiceDate": "23 March 2021",
"sendTo": "Abstractors and Design Co.\nRonald Davis\nSuite 8\n611 Maine St\nSan Francisco\nCA\n94105",
"items": [
{
"qty": "10",
"ItemName": "ACP101S Standard Support",
"itemDescription": "Initial Hours allocated for access to email and phone support for Premier Version",
"amt": "1100.00"
},
{
"qty": "6",
"ItemName": "ACP101C Screen Customization",
"itemDescription": "Hours spent customizing screens in Premier Version for client requirements",
"amt": "660.00"
},
{
"qty": "4.5",
"ItemName": "ACP101R Report Customization",
"itemDescription": "Hours spent customizing reports in Premier Version for client requirements",
"amt": "495.00"
},
{
"qty": "2",
"ItemName": "ACP101I System Imports",
"itemDescription": "Hours spent importing customer records into Premier Version",
"amt": "220.00"
},
{
"qty": "3",
"ItemName": "ACP100 Accounting Package",
"itemDescription": "Annual Subscription to Standard Version of Accounts System",
"amt": "900.00"
},
{
"qty": "4.5",
"ItemName": "ACP100T Online Training",
"itemDescription": "Hours of Training in Standard Version - Interactive Demos with Q&A Sessions",
"amt": "495.00"
}
]
}
```
--------------------------------
### Tornado: Create PDF using Python
Source: https://resources.docmosis.com/search?category_id=8&isc=1&issearch=1&ordering=zelevance
This example demonstrates generating a PDF from a DOCX template using Python by calling the Docmosis REST API. Ensure the API is accessible and the template exists.
```python
import requests
import json
url = "http://localhost:8080/api/convert/render"
data = {
"name": "Docmosis",
"version": "Tornado"
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, data=json.dumps(data), headers=headers)
if response.status_code == 200:
with open('output.pdf', 'wb') as f:
f.write(response.content)
print("PDF generated successfully!")
else:
print(f"Error: {response.status_code}")
print(response.text)
```
--------------------------------
### Container Data Array Example
Source: https://resources.docmosis.com/example-templates/template-for-generating-bill-of-lading
Provides an example of an array named 'ctrs' used to store container data, including type, number, seal number, and quantity.
```JSON
"ctrs": [
{
"type": "10' CONTAINER NO: ",
"no": "EXGU3024389-2",
"seal": "SEAL NO: 555728",
"qty": "220"
},
{
"type": "10' CONTAINER NO: ",
"no": "EXGU3024111-5",
"seal": "SEAL NO: 555111",
"qty": "150"
},
{
"type": "10' CONTAINER NO: ",
"no": "EXGU3024132-6",
"seal": "SEAL NO: 555423",
"qty": "210"
}
]
```
--------------------------------
### Docmosis-Java - Create PDF via API
Source: https://resources.docmosis.com/code-samples
Demonstrates the simplest way to create a PDF document using Docmosis-Java with a DOCX template. Includes SimpleRender.java, WelcomeTemplate.docx, and readme.txt.
```Java
public class SimpleRender {
public static void main(String[] args) throws Exception {
// Java code for simple PDF rendering
}
}
```
--------------------------------
### Docmosis-Java: Configure using Properties Files
Source: https://resources.docmosis.com/code-samples/docmosis-java/latest
Shows how to configure Docmosis using properties and configuration files. Requires docmosis.properties and converterPoolConfig.xml.
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.docmosis.common.DocmosisException;
import org.docmosis.common.DocmosisProcessor;
import org.docmosis.common.DocmosisProcessorFactory;
public class DocmosisConfigFiles {
public static void main(String[] args) {
// The template file to use
File templateFile = new File("WelcomeTemplate.docx");
// The output PDF file
File outputFile = new File("output.pdf");
// The data to be merged into the template (can be null)
// For this example, we don't need any data
String data = null;
// Load configuration from properties and XML files
// Ensure docmosis.properties and converterPoolConfig.xml are in the classpath
// or specify their paths directly.
// Example: DocmosisProcessor processor = DocmosisProcessorFactory.getDocmosisProcessor("path/to/docmosis.properties", "path/to/converterPoolConfig.xml");
DocmosisProcessor processor = DocmosisProcessorFactory.getDocmosisProcessor();
try {
// Render the document using the configured processor
processor.process(templateFile, data, outputFile);
System.out.println("Successfully created " + outputFile.getName() + " using configured properties.");
} catch (DocmosisException e) {
System.err.println("Error rendering document: " + e.getMessage());
e.printStackTrace();
}
}
}
```
--------------------------------
### Tornado: Create PDF using Ruby
Source: https://resources.docmosis.com/search?category_id=8&isc=1&issearch=1&ordering=zelevance
This example shows how to generate a PDF from a DOCX template using Ruby. It calls the Docmosis REST API to merge data with the template.
```ruby
require 'rest-client'
require 'json'
url = "http://localhost:8080/api/convert/render"
data = {
"name": "Docmosis",
"version": "Tornado"
}
headers = {
'Content-Type': 'application/json'
}
response = RestClient.post(url, data.to_json, headers: headers)
if response.code == 200
File.open('output.pdf', 'wb') do |f|
f.write(response.body)
end
puts "PDF generated successfully!"
else
puts "Error: #{response.code}"
puts response.body
end
```
--------------------------------
### Conditional Question Example
Source: https://resources.docmosis.com/example-templates/generate-disclosure-form-from-template
Use conditional expressions to control the visibility of questions based on previous answers. This example shows a question that only appears if the answer to a prior question is not 'Never'.
```Docmosis
<>
```
--------------------------------
### Field Formatting Example
Source: https://resources.docmosis.com/example-templates/template-for-generating-bill-of-lading
Illustrates how formatting applied to the second angled bracket of a field tag controls the output format. The example shows logic in green text and the final output in a larger black font.
```Docmosis Templating
<<><><><>><>><><>
```
--------------------------------
### Simple PDF Creation with Docmosis-Java
Source: https://resources.docmosis.com/code-samples/docmosis-java-create-a-pdf-via-api
This Java code snippet initializes the Docmosis system, prepares data for a template, and renders a PDF document. Ensure your license key, office path, and template file are correctly configured.
```java
import java.io.File;
import com.docmosis.SystemManager;
import com.docmosis.document.DocumentProcessor;
import com.docmosis.template.population.DataProviderBuilder;
import com.docmosis.util.Configuration;
/**
* A simple example showing Docmosis creating a PDF with dynamic data from a
* DOCX template.
*/
public class SimpleRender
{
public static void main(String[] args)
{
String key = new String("XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-X-XXXX");
String site = new String("Free Trial Java");
String officePath = new String("C:/Program Files/LibreOffice 5");
if (key.startsWith("XXXX")) {
System.err.println("\nPlease set your license key");
System.exit(1);
}
if (!new File(officePath).isDirectory() || !new File(officePath).canRead()) {
System.err.println("\nPlease check \"officePath\" is set to the " +
"install dir for OpenOffice or LibreOffice");
System.exit(1);
}
// Create the initialisation configuration
Configuration config = new Configuration(key, site, officePath);
// Tell Docmosis to use one embedded converter
config.setConverterPoolConfiguration("1");
// Use the DataProviderBuilder to build the data provider from a String array.
DataProviderBuilder dpb = new DataProviderBuilder();
dpb.add("date", "12 Nov 2015");
dpb.add("message", "This Docmosis document engine is working!");
try {
// Initialise the system based on configuration
SystemManager.initialise(config);
File templateFile = new File("WelcomeTemplate.docx");
File outputFile = new File("newDocument.pdf");
if (!templateFile.canRead()) {
System.err.println("\nCannot find '" + templateFile + "' in: " + new File("").getCanonicalPath());
} else {
// Create the document
DocumentProcessor.renderDoc(templateFile, outputFile, dpb.getDataProvider());
System.out.println("\nCreated: " + outputFile.getCanonicalPath());
}
} catch (Exception e){
System.err.println("\nPlease check the following: " + e.getMessage());
} finally {
// shutdown the system
SystemManager.release();
}
}
}
```
--------------------------------
### Docmosis-Java: Create PDF via API
Source: https://resources.docmosis.com/code-samples/docmosis-java/latest
Demonstrates the simplest method to create a PDF document using a template. Ensure you have the WelcomeTemplate.docx and readme.txt from the ZIP.
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.docmosis.common.DocmosisException;
import org.docmosis.common.DocmosisProcessor;
import org.docmosis.common.DocmosisProcessorFactory;
public class SimpleRender {
public static void main(String[] args) {
// The template file to use
File templateFile = new File("WelcomeTemplate.docx");
// The output PDF file
File outputFile = new File("output.pdf");
// The data to be merged into the template (can be null)
// For this example, we don't need any data
String data = null;
// Get a DocmosisProcessor instance
DocmosisProcessor processor = DocmosisProcessorFactory.getDocmosisProcessor();
try {
// Render the document
processor.process(templateFile, data, outputFile);
System.out.println("Successfully created " + outputFile.getName());
} catch (DocmosisException e) {
System.err.println("Error rendering document: " + e.getMessage());
e.printStackTrace();
}
}
}
```
--------------------------------
### Get Template Structure
Source: https://resources.docmosis.com/code-samples/cloud-get-template-structure-using-java-via-api
This Java code snippet shows how to call the Docmosis REST API to get the structure of a specified template. The response is returned in JSON format, detailing the template's fields, images, and sections.
```APIDOC
## POST /api/getTemplateStructure
### Description
Retrieves the structure of a specified template in JSON format. This structure includes details about fields, images, and sections within the template.
### Method
POST
### Endpoint
https://{region}.dws4.docmosis.com/api/getTemplateStructure
### Parameters
#### Query Parameters
- **accessKey** (string) - Required - Your Docmosis Cloud access key.
- **templateName** (string) - Required - The path to the template file on the Docmosis Cloud.
### Request Example
```java
// Example of building the request parameters
final String templateName = "samples/WelcomeTemplate.docx";
final String params = "accessKey=" + ACCESS_KEY + "&templateName=" + templateName;
```
### Response
#### Success Response (200)
- **templateStructure** (object) - An object containing the detailed structure of the template, including fields, images, and sections.
#### Response Example
```json
{
"templateStructure": {
"fields": [
{
"name": "fieldName",
"type": "text"
}
],
"images": [
{
"name": "imageName"
}
],
"sections": [
{
"name": "sectionName"
}
]
}
}
```
```
--------------------------------
### Get Template Structure using C#
Source: https://resources.docmosis.com/code-samples/tornado-get-template-structure-using-c-via-api
This C# code calls the Docmosis REST API to get the structure of a specified template. It handles HTTP requests and responses, including error processing and JSON formatting. Proxy settings can be configured if needed.
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace Docmosis
{
///
/// This sample code shows how to get the structure of the "WelcomeTemplate.docx" template in JSON format
/// via the local Tornado server (localhost:8080).
///
/// If you wish to test via a web proxy server, see the PROXY_* settings below to enable it.
///
///
/// Copyright Docmosis 2019
///
class CSGetTemplateStructureExample
{
private static string DWS_GETSTRUCTURE_URL = "http://localhost:8080/api/getTemplateStructure";
// Set your access key here. The access key is only required if configured in Tornado.
private const string ACCESS_KEY = "";
// the name of the template (stored in Tornado) to use
private const string TEMPLATE = "WelcomeTemplate.docx";
// Proxy settings if needed to reach the internet
private const string PROXY_HOST = "";
private const string PROXY_PORT = "";
private const string PROXY_USER = "";
private const string PROXY_PASSWD = "";
static void Main(string[] args)
{
HttpWebResponse response;
try
{
response = sendRequest();
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
String responseString = getJsonResponse(response.GetResponseStream());
Console.Out.WriteLine(JsonHelper.FormatJson(responseString));
}
else
{
processError(response);
}
}
finally
{
response.Close();
}
}
catch (WebException e)
{
Console.WriteLine("ERROR:" + e.Message);
using (WebResponse webResponse = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)webResponse;
processError(httpResponse);
}
}
catch (Exception e)
{
Console.Error.WriteLine("Unable to connect to Docmosis: " + e.Message);
Console.Error.WriteLine(e.StackTrace);
Console.Error.WriteLine("If you have a proxy, configure proxy settings at the top of this example.");
Console.ReadKey();
System.Environment.Exit(2);
}
Console.Out.WriteLine("Press any key");
Console.ReadKey();
}
///
/// Sends the request to the server and returns the response.
///
///
/// the response returned by the server
///
static HttpWebResponse sendRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(DWS_GETSTRUCTURE_URL);
if (PROXY_HOST.Length != 0)
{
WebProxy proxy = new WebProxy(PROXY_HOST + ":" + PROXY_PORT, true);
if (PROXY_USER.Length != 0)
{
proxy.Credentials = new NetworkCredential(PROXY_USER, PROXY_PASSWD);
}
Console.WriteLine(proxy.Address);
request.Proxy = proxy;
}
string getStructureRequest = buildRequest();
Console.WriteLine("Sending request:" + getStructureRequest);
byte[] data = new UTF8Encoding().GetBytes(getStructureRequest);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
return (HttpWebResponse)request.GetResponse();
}
///
/// Build the request in urlencoded format.
///
private static string buildRequest()
{
StringBuilder sb = new StringBuilder();
// Build the request
sb.Append("accessKey=").Append(ACCESS_KEY).Append("&");
sb.Append("templateName=").Append(TEMPLATE);
return sb.ToString();
}
///
/// Extract the returned json from the response
///
///the Stream containing the content
```
--------------------------------
### Get Template Structure using Java
Source: https://resources.docmosis.com/CodeSamples/Tornado/GetTemplateStructureExample.java
This Java code snippet shows how to call the Tornado API to get the structure of a specified template. It handles connection, request building, sending, and response processing, including error handling. Ensure Tornado is running and accessible at the specified URL.
```java
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.docx" 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/api/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.docx";
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();
}
}
}
}
```
--------------------------------
### Python - Render PDF from DOCX Template
Source: https://resources.docmosis.com/code-samples/cloud-create-a-pdf-using-python-via-api
This example demonstrates how to use Python to call the Docmosis Cloud service to render a PDF from a specified DOCX template. Ensure you have a Docmosis Cloud account and replace 'XXX' with your actual access key. The code handles different regional endpoints and streams the generated PDF.
```python
# 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)
```