<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: EDocGen</title>
    <description>The latest articles on DEV Community by EDocGen (@edocgen).</description>
    <link>https://dev.to/edocgen</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F929988%2F24324799-9507-422d-8a07-3d4c7dec67b0.jpg</url>
      <title>DEV Community: EDocGen</title>
      <link>https://dev.to/edocgen</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/edocgen"/>
    <language>en</language>
    <item>
      <title>Template-Based PDF Document Generation in JavaScript</title>
      <dc:creator>EDocGen</dc:creator>
      <pubDate>Wed, 21 Sep 2022 11:05:26 +0000</pubDate>
      <link>https://dev.to/edocgen/template-based-pdf-document-generation-in-javascript-39gp</link>
      <guid>https://dev.to/edocgen/template-based-pdf-document-generation-in-javascript-39gp</guid>
      <description>&lt;p&gt;Document generation is a very common requirement in the life of a developer. Whether it is an e-commerce site, Management app, or anything. It can be invoice generation, insurance document preparation, doctor's prescription, HR Offer generation, and Payslip generation and you could think of tons of use cases.  There always will be a need for document generation.&lt;/p&gt;

&lt;p&gt;From a developer's perspective, there are a few common approaches to getting this job done. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create HTML elements and print them to generate the documents&lt;/li&gt;
&lt;li&gt;Using some library to generate the documents&lt;/li&gt;
&lt;li&gt;Letting the server handle document generation based on a static template&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These approaches didn't help me. The clients want to have their documents customized by themself. I have been searching for an approach and found &lt;a href="https://www.edocgen.com"&gt;eDocGen &lt;/a&gt;as a single-point solution. &lt;/p&gt;

&lt;p&gt;Unlike other services, eDocGen provides RestAPI that can be integrated into our application.&lt;/p&gt;

&lt;p&gt;In this article, we will discuss how we can integrate eDocGen into our js application to generate documents from various data formats like JSON/XML/Database schema. Please get your free trial to get started with the coding.&lt;/p&gt;

&lt;p&gt;Let's dive in and write code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Setup
&lt;/h2&gt;

&lt;p&gt;For the demo purpose, I have created a sample js application that runs on Node.js. &lt;/p&gt;

&lt;p&gt;Please follow the step below to set up a coding playground for us.&lt;br&gt;
&lt;strong&gt;Step 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;npm init&lt;/code&gt;to create package.json&lt;br&gt;
Step 2:&lt;/p&gt;

&lt;p&gt;Add &lt;code&gt;axios, form-data, request, xhr2&lt;/code&gt; dependencies needed for developing this application using n&lt;code&gt;pm install axios form-data request xhr2&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Step 3:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We need an index file that will act as the starting point of our application. Create an index.js file in the root directory and modify package.json like below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JSON
"scripts": {
    "start": "node index.js"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have a basic application to start with. End of these steps, the package.json should look like something below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JSON
{
  "name": "nodejs-multiple-upload-files",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "axios": "^0.27.2",
    "form-data": "^4.0.0",
    "request": "^2.88.2",
    "xhr2": "^0.2.1"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Login
&lt;/h2&gt;

&lt;p&gt;Though the article is about document generation, we need to log in to get our access token. It's a typical &lt;a href="https://jwt.to"&gt;JWT &lt;/a&gt;token that will be used for authorizing the document generation API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JavaScript

var XMLHttpRequest = require("xhr2");
var xhr = new XMLHttpRequest();
module.exports.getToken = function (callback) {
  var data = JSON.stringify({
    username: "&amp;lt;your username&amp;gt;",
    password: "&amp;lt;password&amp;gt;",
  });

  xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
      token = JSON.parse(this.responseText).token;
      console.log("User Token", token);
      callback(token);
    }
  });

  xhr.open("POST", "https://app.edocgen.com/login");
  xhr.setRequestHeader("content-type", "application/json");
  xhr.setRequestHeader("cache-control", "no-cache")
  xhr.send(data);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can cache the token in the application for a time period less than the expiration time and use it to generate documents or upload templates. After the expiration time, we can refresh the token. The cache can be Redis or an in-memory cache. It's up to your application design.&lt;/p&gt;

&lt;h2&gt;
  
  
  Template Design
&lt;/h2&gt;

&lt;p&gt;As explained above, eDocGen lets the users customize and upload the templates. But how will the data be mapped dynamically? There are certain rules that map the data to the document. We will see how to create a template with the rules.&lt;/p&gt;

&lt;p&gt;Take a look at this document.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0pUvdxE---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6cwfzhauqh7ge5aamd16.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0pUvdxE---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6cwfzhauqh7ge5aamd16.png" alt="Image description" width="880" height="631"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;eDocGen uses tags that are enclosed by &lt;code&gt;{}&lt;/code&gt; for the dynamic fields. We can dynamically add text, logos, tables, conditional statements, mathematical calculations, etc.&lt;/p&gt;

&lt;p&gt;For example, in the image above, &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;String fields:&lt;/strong&gt; &lt;code&gt;{Invoice_Number}&lt;/code&gt; and &lt;code&gt;{Invoice_Date}&lt;/code&gt; are configured to be replaced as text in the template. Anything inside &lt;code&gt;{}&lt;/code&gt; in the template will be matched with input data and replaced.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dynamic Tables:&lt;/strong&gt; Dynamic tables would be a go-on option when there is an array of data that needs to be looped and replaced in a table. The row in the table starts with &lt;code&gt;{#tablename}&lt;/code&gt; and ends with &lt;code&gt;{/tablename}&lt;/code&gt;. In the example above, a row in the invoice table is started with &lt;code&gt;{#IT}&lt;/code&gt; in the first column and ended with &lt;code&gt;{/IT}&lt;/code&gt; in the last column. Columns in the rows can have String fields. In our example, &lt;code&gt;{Item_description}&lt;/code&gt; and &lt;code&gt;{Amount}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Image:&lt;/strong&gt; eDocGen offers to add images dynamically to the template. Follow the steps below. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;    Upload the image to the eDogGen that should respond with an image_id.&lt;/li&gt;
&lt;li&gt;    &lt;code&gt;{%image_id}&lt;/code&gt; is the tag for populating images. The image will be fetched by &lt;code&gt;image_id&lt;/code&gt; from eDocGen storage and replaced in the place of &lt;code&gt;{%image_id}&lt;/code&gt;. The &lt;code&gt;image_id&lt;/code&gt; is expected to be present in the input data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conditional-based Dynamic fields (If-Else):&lt;/strong&gt; Displaying content conditionally can be done with the Conditional tags. For example, When the language is English, &lt;code&gt;{#language == "english"}&lt;/code&gt; English content will be displayed in the document. Likewise, multiple languages can be supported in a single document template.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mathematical calculations:&lt;/strong&gt; eDocGen supports mathematical calculations based on formulae defined in the template. The summation of the amount of the items in the invoice can be calculated using the below formulae.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JSON

{
    IT // array of items
    | summation:'Amount' // value that needs to be used for calculation 
    | format_number: ",” // format of the value
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please head over to &lt;a href="https://www.edocgen.com/examples/json-to-pdf"&gt;JSON-to-pdf&lt;/a&gt; for more details.&lt;/p&gt;

&lt;h2&gt;
  
  
  Template Upload
&lt;/h2&gt;

&lt;p&gt;Once the template is prepared, this can be uploaded for consumption. There are two ways. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;    eDocGen's interactive UI - which has integration with dropbox, drive, Evernote&lt;/li&gt;
&lt;li&gt;    eDocGen's RestAPI - which can be integrated into the client code for uploading templates.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For the demo, purpose I have used the UI for uploading the template. On the successful upload, we get an ID as a response. This is the ID that will be used for generating the documents.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LFS_ZFIM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0z9oowcj9b1t452eld9j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LFS_ZFIM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0z9oowcj9b1t452eld9j.png" alt="Document generation template" width="622" height="743"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Leaving here the Upload API structure for your reference, in case you wish to use API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JSON

"/api/v1/document": {
  "post": {
    "tags": [
      "Document"
    ],
    "description": "Upload template to eDocGen",
    "produces": [
      "application/json"
    ],
    "consumes": [
      "multipart/form-data"
    ],
    "parameters": [
      {
        "name": "documentFile",
        "description": "file to upload",
        "required": true,
        "type": "file",
        "in": "formData"
      },
      {
        "name": "x-access-token",
        "in": "header",
        "description": "JWT auth token from login",
        "required": true,
        "type": "string"
      }
    ],
    "responses": {
      "200": {
        "description": "Successfully uploaded document file"
      },
      "other": {
        "description": "Operation failed"
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  JSON to Document Generation
&lt;/h2&gt;

&lt;p&gt;Now we have our template ready. Let's generate the document.&lt;/p&gt;

&lt;p&gt;Document generation has two phases.&lt;/p&gt;

&lt;p&gt;1.Request to generate the document&lt;br&gt;
2.Download the document&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1: Request To Generate the Document
&lt;/h2&gt;

&lt;p&gt;We request document generation with the details required and we get an acknowledgment. The process happens behind the screen asynchronously.&lt;br&gt;
&lt;strong&gt;Parameters Needed for the Document Generation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;API: &lt;code&gt;POST - /api/v1/document/generate/bulk&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Request Body&lt;/strong&gt;&lt;br&gt;
Form Data&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---mAWYQyw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgkf750wccwxdbt6uw1n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---mAWYQyw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgkf750wccwxdbt6uw1n.png" alt="Image description" width="727" height="177"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Header&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Qipw-5ms--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfjndzb0n120o613fztk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Qipw-5ms--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfjndzb0n120o613fztk.png" alt="Image description" width="424" height="87"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input Data&lt;/strong&gt;&lt;br&gt;
The data in the inputFile should be in a structure defined by the template. For example, For the above template mapping will be like the below.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Invoice_Number&lt;/code&gt; in JSON should be matching with &lt;code&gt;{Invoice_Number}&lt;/code&gt; in the template. &lt;/li&gt;
&lt;li&gt;For table data, it should be an array of objects, with &lt;code&gt;Item_Description&lt;/code&gt; and &lt;code&gt;Amount&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The amount should be a number for summation calculation.
invoice&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TRm9DDv1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfy04gfb4z7yesd36kae.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TRm9DDv1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfy04gfb4z7yesd36kae.png" alt="Document automation template" width="880" height="415"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2: Download the Document
&lt;/h2&gt;

&lt;p&gt;The generated document can be downloaded using the output ID obtained from the above step and the name of the output file. &lt;/p&gt;

&lt;p&gt;We will use two APIs here. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;    API to know the file's existence : &lt;code&gt;/api/v1/output/name/${fileName}&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;    API to download the file : &lt;code&gt;/api/v1/output/download/${outputId}&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since document generation happens asynchronously, to know whether the document is generated or not, we will use the &lt;code&gt;/api/v1/output/name&lt;/code&gt; api.&lt;/p&gt;

&lt;p&gt;On the success response from API&lt;code&gt;/api/v1/output/name&lt;/code&gt; will download the file.&lt;/p&gt;

&lt;p&gt;I have combined both of these steps in a single js file and it looks below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Java

let login = require("../edocgen_login");
const fs = require("fs");
const uuid = require("uuid");
const FormData = require("form-data");
let axios = require("axios");
let fileName = uuid.v4();
const headers = {
  "Content-Type": "multipart/form-data",
  "x-access-token": "null",
};
const hostName = "https://app.edocgen.com/api/v1/document/generate/bulk";
const outputFormat = "&amp;lt;format&amp;gt;";// pdf / docx
const documentId = "&amp;lt;template_id&amp;gt;";    // id of the template we want to use
module.exports.generateFiles =  function () {
  let authToken = login.getToken(function handleUsersList(token) {
    headers["x-access-token"] = token;
    var formBody = new FormData();
    formBody.append("documentId", documentId);
    formBody.append("format", outputFormat);
    formBody.append("outputFileName", fileName);
    // json data for the template
    formBody.append("inputFile", fs.createReadStream("./JSON_Data_Single.json"));   // local path forjson file
    let config = {
      method: "post",
      url: hostName,
      headers: headers,
      data: formBody,
    };

    console.log(`https://app.edocgen.com/api/v1/output/name/${fileName}.${outputFormat}`);
    let config_output = {
      method: "get",
      url:`https://app.edocgen.com/api/v1/output/name/${fileName}.${outputFormat}`,
      headers: headers,
    };
    const MAX_RETRY = 50;
    let currentRetry = 0;
    // max retry for 50 times
    function errorHandler() {
      if (currentRetry &amp;lt; MAX_RETRY) {
        currentRetry++;
        console.log("Document is not prepared yet! Retrying...");
        sendWithRetry(processResponse);
      } else {

        console.log("No luck. Document is not generated. Retried multiple times.");
      }
    }
    // sendWithRetry checks for file existence
    // on success, it proceeds to download the file
    // on failure, it retries 
    // todo: introduce spin lock
    function sendWithRetry(callback) {
      axios(config_output)
        .then(function (response) {
          if (response.data.output.length !== 1) {
            throw new axios.Cancel("Document is not found. Throw error.");
          } else {
            callback(response);
          }
        })
        .catch(errorHandler);
    }
    axios(config)
      .then(function (response) {
        sendWithRetry(processResponse);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
};

function processResponse(response) {
  const outputId = response.data.output[0]._id;
  console.log(
    "Output Document is Generated. Id = ",
    response.data.output[0]._id
  );
  let config_download = {
    method: "get",
    url: `https://app.edocgen.com/api/v1/output/download/${outputId}`,
    headers: headers,
    responseType: "arraybuffer",
  };
  axios(config_download)
    .then(function (response) {
      console.log("Output file is downloaded " + `${fileName}.${outputFormat}`);
      fs.writeFileSync(`./${fileName}.${outputFormat}`, response.data);
    })
    .catch(function (error) {
      console.log("Error while downloading");
      console.log(error);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Single vs Multiple Documents
&lt;/h2&gt;

&lt;p&gt;When the data is single JSON, a single document of the given format will be generated.&lt;/p&gt;

&lt;p&gt;When the data is an array of objects, documents for each array element will be generated and zipped into a file.&lt;/p&gt;

&lt;h2&gt;
  
  
  XML to Document Generation
&lt;/h2&gt;

&lt;p&gt;The procedure is simple for XML data. All we need to do is pass the XML file in the place of JSON data. &lt;/p&gt;

&lt;p&gt;Like JSON to document, For XML to Document as well, we need documentId, outputFileName, format and inputFile. Everything same as JSON, except the input file, will be an XML file.&lt;/p&gt;

&lt;p&gt;The sample XML data would look like below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;XML
&amp;lt;?xml version="1.0" encoding="UTF-8" ?&amp;gt;
&amp;lt;marker&amp;gt;
  &amp;lt;values&amp;gt;
    &amp;lt;Invoice_Number&amp;gt;SBU-2053501&amp;lt;/Invoice_Number&amp;gt;
    &amp;lt;Invoice_Date&amp;gt;31-07-2020&amp;lt;/Invoice_Date&amp;gt;
    &amp;lt;Terms_Payment&amp;gt;Net 15&amp;lt;/Terms_Payment&amp;gt;
    &amp;lt;Company_Name&amp;gt;ABC company&amp;lt;/Company_Name&amp;gt;
    &amp;lt;Billing_Contact&amp;gt;ABC-Contact1&amp;lt;/Billing_Contact&amp;gt;
    &amp;lt;Address&amp;gt;New york, United State&amp;lt;/Address&amp;gt;
    &amp;lt;Email&amp;gt;support@edocgen.com&amp;lt;/Email&amp;gt;
    &amp;lt;Logo&amp;gt;621cd2b783a6095d7b15a443&amp;lt;/Logo&amp;gt; 
     &amp;lt;Sum1&amp;gt;6,751&amp;lt;/Sum1&amp;gt;
     &amp;lt;para&amp;gt;61b334ee7c00363e11da3439&amp;lt;/para&amp;gt;
    &amp;lt;ITH&amp;gt;
      &amp;lt;Heading1&amp;gt;Item Description&amp;lt;/Heading1&amp;gt;
      &amp;lt;Heading2&amp;gt;Amount&amp;lt;/Heading2&amp;gt;
    &amp;lt;/ITH&amp;gt;
    &amp;lt;IT&amp;gt;
      &amp;lt;Item_Description&amp;gt;Product Fees: X&amp;lt;/Item_Description&amp;gt;
      &amp;lt;Amount&amp;gt;5,000&amp;lt;/Amount&amp;gt;
    &amp;lt;/IT&amp;gt;
  &amp;lt;/values&amp;gt;
&amp;lt;marker&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Code change that I made for XML as the data source is simple as below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JavaScript
var formBody = new FormData();
formBody.append("documentId", documentId);
formBody.append("format", outputFormat);
formBody.append("outputFileName", fileName);
formBody.append("inputFile", fs.createReadStream("./XML_Invoice.xml"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Database to Document Generation
&lt;/h2&gt;

&lt;p&gt;Document generation from Databases is almost the same as other data sources. But in this case, instead of uploading the inputFile, we require to provide the connection details and SQL query.&lt;/p&gt;

&lt;p&gt;The output columns of the SQL query should be matching with the tags in the document template.&lt;/p&gt;

&lt;p&gt;Let's look at how to configure this in code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JavaScript
const templateId = "&amp;lt;template id&amp;gt;";
const dbVendor = "mysql";
const dbUrl = "&amp;lt;jdbc connection URL&amp;gt;";
const dbLimit = "100";
const dbPassword = "&amp;lt;database password&amp;gt;";
const dbQuery = "SELECT JSON_ARRAY(first, last) FROM customers;";
const outputFormat = "pdf";
// form data prepareation
let formBody = new FormData();
formBody.append("documentId", templateId);
formBody.append("format", outputFormat);
formBody.append("dbVendor", dbVendor);
formBody.append("dbUrl", dbUrl);
formBody.append("dbLimit", dbLimit);
formBody.append("dbPassword", dbPassword);
formBody.append("dbQuery", dbQuery);
formBody.append("outputFileName", fileName);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Everything else would remain the same.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sending the Document Over Email
&lt;/h2&gt;

&lt;p&gt;eDocGen provides the facility to send the generated document over Email.&lt;br&gt;
&lt;strong&gt;Parameters Needed for the Document Generation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;API: POST - &lt;code&gt;/api/v1/output/email&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request Body&lt;/strong&gt;&lt;br&gt;
JSON&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--R8RyV_pG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9t2rumxpvjwvhovkz3bx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--R8RyV_pG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9t2rumxpvjwvhovkz3bx.png" alt="Image description" width="568" height="113"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Header&lt;br&gt;
Content-Type    multipart/form-data&lt;br&gt;
x-access-token  JWT auth token from login&lt;/p&gt;

&lt;h2&gt;
  
  
  Code Sample
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let login = require("../edocgen_login");
let axios = require("axios");
const hostName = "https://app.edocgen.com/api/v1/output/email";
const headers = {
  "Content-Type": "application/json",
  "x-access-token": "null",
};

const outId = "&amp;lt;output ID&amp;gt;"; // Put output ID here which need to be sent via email
const emailId = "&amp;lt;user email&amp;gt;"; // Put user email here

module.exports.generateFiles = function () {
  let authToken = login.getToken(function handleUsersList(token) {
    headers["x-access-token"] = token;

    let payload = { outId: outId, emailId: emailId };
    let config = {
      method: "post",
      url: hostName,
      headers: headers,
      data: payload,
    };

    axios(config)
      .then(function (response) {
        console.log("Mail sent");
      })
      .catch(function (error) {
        console.log(error);
      });
  });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The email from eDocGen would look like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6GwjGGfO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hky4gd6ek0vauq4sjsff.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6GwjGGfO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hky4gd6ek0vauq4sjsff.png" alt="Image description" width="880" height="372"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are tons of other features that I couldn't cover here. But I hope this article could provide you with an idea of where to start.&lt;/p&gt;

&lt;p&gt;Will meet you with another exciting article. Have a good day!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>document</category>
      <category>pdf</category>
    </item>
  </channel>
</rss>
