Database to document

PDF and Word Document Generation API

Documents Generator API


Businesses create various documents from their enterprise systems and databases. The most common approach to automate this is by coding for each document template inside the core systems. This makes the code less modular and inflexible. There is minimal code reuse. Moreover, every time a template changes, the associated code requires modifications.

With EDocGen document generation API, business users can use existing templates as-is. They can create/edit PDF, Word, Excel, and PPTX templates in native editors, without installing a separate designer or add-on. This reduces the dependency on the IT team for template changes. All the templates are stored in a central repository with a fine-grained authorization mechanism.

The enterprise document automation microservice helps the creation of documents from various data sources. It also offers pre-built integrations for document distribution. This makes it easy to create document workflows. The API automates document generation and distribution from enterprise applications, and databases.


Document Automation Microservice


Developers can automate document generation with a few lines of code. They can create both on-demand and bulk documents from API.

  1. On-demand Generation - Creation through the synchronous API call. Faster creation and download of the file.
  2. Bulk Generation - The API is built for high performance and generates thousands of complex documents in a few seconds. Since these API calls are asynchronous, you can initiate high-volume requests.

You can generate almost all document formats including Text, Image, Excel, PDF, PPTX, and Word. The REST API is flexible to support every document type and generation scenario across the enterprise.

Dynamic Field Types


It supports the dynamic population of text, tables, content blocks, hyperlinks, and images from Excel data. You can also include conditional statements, calculations, and loops right inside the template.

Text and tables

Supports dynamic population of text, tables, loops, lists, and nested tables.




Images and QR Codes

Populate Base64, Image URLs, QR Codes, Barcodes dynamically.




HTML, Graphs & Charts

The API allows you to populate HTML styles and charts.

JSON Charts and Graphs

Subtemplates, Paragraphs

From a single master template, create variations by populating content blocks.

Apart from this, API also supports multi-lingual document templates, arithmetic calculations, conditional statements (if-else) for generating proposals, invoices, contracts, etc.

Datasources


The microservice allows you to generate them from various data sources including

  1. XML, JSON, and Excel data
  2. Databases including SQL, MySQL, MongoDB, and Oracle
  3. Enterprise systems
  4. Online forms

After generation, you can distribute generated documents through various channels including Email, e-Sign, print, and cloud storage.

The following table summarizes various integrations.

Databases

MySQL, MSSQL, Oracle, MongoDB

E-Sign Providers

DocuSign, SignNow, Signaturely

Document Management Systems (DMS)

SharePoint

Cloud Storage

OneDrive, Box, Google Drive

Email Providers

Amazon SES, SendGrid, Office365, GSuite


Execution Steps


Document generator API

Here are the steps to authentication and making the REST API call to the EDocGen.

  1. API uses token-based web authentication. Register and obtain an access token by passing username and password to /login. Use this token for every API call
  2. Order of actions is Upload template -> Generate documents -> Search Output by name and get ID --> Download
    1. Upload template through Post call
    2. Get the template id.

    3.                           $ curl 'https://app.edocgen.com/api/v1/document/?skipCount=15&limit=15&field=addedAt&sort_direction=-1&tags=none' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0' -H 'Accept: application/json, text/plain, */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'x-access-token: tokenid' | json_pp
      {
         "status" : 200,
         "documents" : [
            {
               ...
               "_id" : "5f61dd26604d2322bb786d8e",
               "name": "test.docx",
            ...
             }
          ]
      }
                            
    4. Generate documents by passing template id and data file

    5.                          curl 'https://app.edocgen.com/api/v1/document/generate/' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0' -H 'Accept: application/json, text/plain, */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/json;charset=utf-8' -H 'x-access-token: tokenid' -H 'Origin: https://app.edocgen.com' -H 'Connection: keep-alive' -H 'Referer: https://app.edocgen.com/template/' -H 'Cookie: continually_user_id=3eyk8pxzw6rn; _ga=GA1.2.1505829491.1596462685; x-session-id=s%3A4dezI-EfFmWK4ikHM9HirDfLq37ZHviq.mwKON5WAuvOQfBs8wF3tOgQYGSUhnd0KyhhgNWXQlAfbdg' --data-raw '{"markers":{"ATM":"1234567","MA":[{"SNo":"1","Local_Time":"12:00:01","Type":"Time","Currency":"$","Amount":"350","Cash_Amount":"300","Discount":"10","Profit":"50","Your_Share":"30"}],"Sum":"450"},"documentId":"5f61dd26604d2322bb786d8e","async":true,"format":"pdf","outputFileName":"Output.pdf"}'
      Post data:
      {
        "markers": {
          "ATM": "1234567",
          "MA": [
            {
              "SNo": "1",
              "Local_Time": "12:00:01",
              "Type": "Time",
              "Currency": "$",
              "Amount": "350",
              "Cash_Amount": "300",
              "Discount": "10",
              "Profit": "50",
              "Your_Share": "30"
            }
          ],
          "Sum": "450"
        },
        "documentId": "5f61dd26604d2322bb786d8e",
        "async": true,
        "format": "pdf",
        "outputFileName": "Output.pdf"
      }
      
                            
    6. Query for output files by name using /api/v1/output/name/{name}. Get the document identifier from the response. The file will only be available after a successful generation. To identify any problems with document generation, query events using /api/v1/events?startIndex=<startIndex>&endIndex=<endIndex>
    7. For downloading the output file, once id and token are known, you can simply do a get to https://app.edocgen.com/api/v1/output/download/<id>?access_token=<access-token>. On clicking this URL, the browser automatically asks for saving the output file. For bulk generation, the output is a zip file.

Programming Language Support


REST API can be consumed either as SAAS or can be deployed on on-premise servers to accommodate your specific performance and security needs. With the RESTful API, the document generation becomes modular. Applications make a call to the API server and the API returns the desired output.

Generate PDF and Word documents from practically any programming environment. It doesn’t matter what language and platform you are using because you make browser calls to API working in your preferred programming environment :

  1. JavaScript
  2. PHP
  3. Python
  4. Ruby
  5. Java
  6. C#
  7. VB.NET

Python Asyc Python Sync C#JavaScript
                           
                            

import requests import uuid import os.path import json url = "https://app.edocgen.com/login" payload = "{\n\t\"username\":\"support@edocgen.com\",\n\t\"password\": \"password\"\n}" headers = { 'content-type': "application/json", 'cache-control': "no-cache", 'postman-token': "0ba8be97-557e-fee5-08d6-d05c5eee4710" } response = requests.request("POST", url, data=payload, headers=headers) x_access_token = response.json()['token'] print ("Using %s for further requests." % x_access_token) # upload template url = "https://app.edocgen.com/api/v1/document" headers = { 'x-access-token': x_access_token } template_file = "/Users/usrname/Downloads/name.docx" files = {'documentFile': open(template_file,'rb')} values = {} response = requests.post(url, files=files, data=values, headers=headers) template_id = response.json()['id'] print("uploaded document %s with id: %s" %(template_file, template_id)) #Generate request url = "https://app.edocgen.com/api/v1/document/generate" # the output file extension will be added automatically by the edocgen system outputFileName = "%s.docx" %uuid.uuid4() generated_format = "docx" inputValues = { 'documentId': template_id, 'format': generated_format, 'outputFileName': outputFileName, 'markers': { 'name': 'name', 'password': 'guess_what' } } headers['content-type'] = 'application/json' response = requests.post(url, data=json.dumps(inputValues), headers=headers) print("Generate document: %s" % response.json()) #Wait for file to get generated and download url = "https://app.edocgen.com/api/v1/output/name/%s" % outputFileName print("Fetching files with name using url: %s" %url) response = requests.get(url, headers=headers) output = response.json()["output"][0] if "output" in response.json() and len(response.json()["output"]) > 0 else None generated_file_id = None while(not output): print("waiting for file to get generated...") response = requests.get(url, headers=headers) output = response.json()["output"][0] if "output" in response.json() and len(response.json()["output"]) > 0 else None generated_file_id = output["_id"] print("generated file id: %s" % generated_file_id) # Download the generated file url = 'https://app.edocgen.com/api/v1/output/download/%s' % generated_file_id download_to_file = "/tmp/downloaded.%s" % generated_format response = requests.get(url, headers=headers, allow_redirects=True) open(download_to_file, 'wb').write(response.content) print("File downloaded successfully: %s" % os.path.isfile(download_to_file)) # Delete Template url = "https://app.edocgen.com/api/v1/document/%s" % template_id response = requests.delete(url, headers=headers) print("Deleted template: %s" %response.json()) # Logout url = "https://app.edocgen.com/api/v1/logout" response = requests.post(url, headers=headers) print("Logged out of eDocGen: %s" % response.json())

                          
                            

import requests import uuid import os.path import json url = "https://app.edocgen.com/login" payload = "{\n\t\"username\":\"support@edocgen.com\",\n\t\"password\": \"your_random_password\"\n}" headers = { 'content-type': "application/json", 'cache-control': "no-cache", } response = requests.request("POST", url, data=payload, headers=headers) x_access_token = response.json()['token'] print ("Using %s for further requests." % x_access_token) # upload template url = "%s/api/v1/document" %(base_url) headers = { 'x-access-token': x_access_token } template_file = "/Users/usrname/Downloads/name.docx" files = {'documentFile': open(template_file,'rb')} values = {} response = requests.post(url, files=files, headers=headers) template_id = response.json()['id'] print("uploaded document %s with id: %s" %(template_file, template_id)) #Generate request url = "%s/api/v1/document/generate" %(base_url) # the output file extension will be added automatically by the edocgen system outputFileName = "%s.docx" %uuid.uuid4() generated_format = "docx" inputValues = { 'sync': True, 'documentId': template_id, 'format': generated_format, 'outputFileName': outputFileName, 'markers': { 'name': 'YourName', 'password': 'guess_what' } } headers['content-type'] = 'application/json' response = requests.post(url, data=json.dumps(inputValues), headers=headers) download_to_file = "/tmp/downloaded.%s" % generated_format open(download_to_file, 'wb').write(response.content) print("File downloaded successfully: %s" % os.path.isfile(download_to_file)) # Delete Template url = "%s/api/v1/document/%s" %(base_url, template_id) response = requests.delete(url, headers=headers) print("Deleted template: %s" %response.json()) # Logout url = "%s/api/v1/logout" %(base_url) response = requests.post(url, headers=headers) print("Logged out of eDocGen: %s" % response.json())

                          
                            

public static string GenerateDoc2(string templateId, string markers, ref string exceptionMsg) { string authEndpoint = "https://app.edocgen.com/api/v1/document/generate"; QuoteReqToeDocGen quoteReq = new QuoteReqToeDocGen(); quoteReq.documentId = templateId; quoteReq.markers = markers; quoteReq.format = "word"; quoteReq.outputFileName = "outputFile"; string requestBody = JsonConvert.SerializeObject(quoteReq); Uri myUri = new Uri(authEndpoint, UriKind.Absolute); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUri); request.Method = "POST"; request.Headers["content-type"] = "application/json"; request.Headers["x-access-token"] = GetToken.GetBearerToken(ref exceptionMsg); using (Stream webStream = request.GetRequestStream()) using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII)) { requestWriter.Write(requestBody); } try { WebResponse webResponse = request.GetResponse(); using (Stream webStream = webResponse.GetResponseStream()) { if (webStream != null) { using (StreamReader responseReader = new StreamReader(webStream)) { string response = responseReader.ReadToEnd(); } } } return ""; } catch (Exception ex) { exceptionMsg = ex.Message; throw ex; } }

                          
                            

// Login var data = JSON.stringify({ "username": "support@edocgen.com", "password": "password" }); var xhr = new XMLHttpRequest(); //xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { token = JSON.parse((this.responseText)).token; console.log("User Token", token) } }); xhr.open("POST", "https://app.edocgen.com/login"); xhr.setRequestHeader("content-type", "application/json"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.setRequestHeader("postman-token", "0fc878b0-ff0a-0dd2-28dc-9caeed2f144a"); xhr.send(data); //Upload Template var data = new FormData(); data.append("documentFile", "APITest01.docx"); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { var templateId = JSON.parse(this.responseText).id; console.log('uploaded document id:', templateId) } }); xhr.open("POST", "https://app.edocgen.com/api/v1/document"); xhr.setRequestHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0aG9saXlhLnJhdmlAZ21haWwuY29tIiwiZXhwIjoxNTYxMzUwMDI0ODk3fQ.urP_RkcxUlTXf2bB3UYLflZYyBCRkIv_Jxgai3k-U5A"); xhr.send(data); //Single document generation var data = JSON.stringify({ "documentId": "5cdbfe0745f7b9028c1d89eb", "markers": "{'field1':'value1', 'field2':'value2'}", "format": "pdf", "outputFileName": "test.pdf" }); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); // Will output success message } }); xhr.open("POST", "https://app.edocgen.com/api/v1/document/generate"); xhr.setRequestHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0aG9saXlhLnJhdmlAZ21haWwuY29tIiwiZXhwIjoxNTYxMzUwMDI0ODk3fQ.urP_RkcxUlTXf2bB3UYLflZYyBCRkIv_Jxgai3k-U5A"); xhr.setRequestHeader("content-type", "application/json"); xhr.send(data); //Get generated document by name var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { var res = JSON.parse(this.responseText); var generated_file_id = res.output[0]._id; // Search by name can return multiple files. console.log("Generated file id: ", generated_file_id); } }); xhr.open("GET", "https://app.edocgen.com/api/v1/output/name/test.pdf"); // test.pdf: filename as provided while requesting document generate xhr.setRequestHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0aG9saXlhLnJhdmlAZ21haWwuY29tIiwiZXhwIjoxNTYxMzUwMDI0ODk3fQ.urP_RkcxUlTXf2bB3UYLflZYyBCRkIv_Jxgai3k-U5A"); xhr.send(data); //Download file var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("GET", "https://app.edocgen.com/api/v1/output/download/5d0a5d5339c8133284d212ad"); // generated id received by querying output files by name xhr.setRequestHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0aG9saXlhLnJhdmlAZ21haWwuY29tIiwiZXhwIjoxNTYxMzUwMDI0ODk3fQ.urP_RkcxUlTXf2bB3UYLflZYyBCRkIv_Jxgai3k-U5A"); xhr.send(data);



Frequently Asked Questions


Is it possible to create password-protected PDFs with watermarks?

Yes, you can generate password-protected PDFs with watermarks. The instructions for opening the PDF can be sent to the user via email along with the attachment.

Can I populate a template with multiple data sources?

Yes, you can create drafts and update them by populating data from multiple data sources till you generate the desired final output.

Do you support Office365?

Yes. You can generate documents with your templates and data files residing in OneDrive.

What are the delivery options available for assembled documents?

1. Download generated documents. Files are optimized for mobile browser download.

2. Email generated files to the individual recipient.

3. Sync generated files to OneDrive or SharePoint DMS.

4. Send them for E-Sign.

5. Print.


Popular Posts