This example shows how to generate a PDF from a DOCX template using C#. It calls the Docmosis REST API, sending the render instructions and data as XML, 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.
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 "samples/WelcomeTemplate.docx" template using XML 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:
///
/// ACCESS_KEY - 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 is likely because you have a proxy server you need to
/// configure. See the PROXY_* settings below to enable it.
///
///
/// Copyright Docmosis 2019
///
class CSRenderExample
{
// Set your region here.
// End-point in the USA
private static string DWS_RENDER_URL = "https://us1.dws4.docmosis.com/api/render";
// End-point in the EU
// private static string DWS_RENDER_URL = "https://eu1.dws4.docmosis.com/api/render"
// End-point in AUS
// private static 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 const string ACCESS_KEY = "XXXXX";
// 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 our cloud account) to use
private const string TEMPLATE = "samples/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)
{
if (ACCESS_KEY.Equals("XXXXX", StringComparison.Ordinal))
{
Console.Error.WriteLine("Please set your private ACCESS_KEY at the top of this file from your Docmosis cloud account.");
Console.Out.WriteLine("Press any key");
Console.ReadKey();
System.Environment.Exit(1);
}
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 the docmosis cloud: " + 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/xml; 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 XML format. You can do it in JSON if you prefer (code not shown here).
///
private static string buildRequest()
{
StringBuilder sb = new StringBuilder();
// Start building the instruction
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
sb.Append("<render");
sb.Append(" accessKey=\"").Append(ACCESS_KEY).Append("\"");
sb.Append(" templateName=\"").Append(TEMPLATE).Append("\"");
sb.Append(" outputName=\"").Append(OUTPUT_FILE).Append("\"");
sb.Append(" outputFormat=\"").Append(OUTPUT_FORMAT).Append("\"");
sb.Append(">\n");
// now add the data specifically for this template
string[] messages = { "This cloud thing is better than I thought.",
"The sun is shining",
"Right, now back to work." };
sb.Append(" <data>\n");
sb.Append(" <title>Welcome to Docmosis in the Cloud</title>\n");
for (int i = 0; i < messages.Length; i++)
{
sb.Append(" <messages>\n");
sb.Append(" <msg>").Append(messages[i]).Append("</msg>\n");
sb.Append(" </messages>\n");
}
sb.Append(" </data>\n");
// end the entire instruction
sb.Append("</render>\n");
return sb.ToString();
}
///
/// Save the given Input stream to a file
///
///the Stream containing the content to save
private static void saveToFile(Stream content)
{
byte[] buff = new byte[1000];
int bytesRead = 0;
FileStream file = File.Create(OUTPUT_FILE);
try
{
while ((bytesRead = content.Read(buff, 0, buff.Length)) > 0)
{
file.Write(buff, 0, bytesRead);
}
}
finally
{
file.Close();
}
Console.Out.WriteLine("Created file:" + file.Name);
}
///
/// Something went wrong in the call to the service, tell the user about it
///
///The response causing errors
private static void processError(HttpWebResponse response)
{
Console.Error.WriteLine("Our call failed: status = {0}", response.StatusCode);
Console.Error.WriteLine("message:" + response.StatusDescription);
StreamReader errorReader = new StreamReader(response.GetResponseStream());
String msg;
while ((msg = errorReader.ReadLine()) != null)
{
Console.Error.WriteLine(msg);
}
}
}
}
