PDF Generaor API

PDF Generation API - Generate PDFs in batch from existing templates

Use Cases for PDF Generation API


The PDF Generator API offers a wide range of use cases for developers across different industries. Here are a few examples:

  1. Invoicing and Reporting: For businesses that generate a large volume of invoices or reports, the API can automate the process of creating PDF documents based on the provided data and document template. This ensures consistency and accuracy while saving time.
  2. Contracts and Agreements: Legal professionals and organizations can leverage the API to generate contracts and agreements dynamically. By populating predefined contract templates with relevant data, it becomes effortless to create customized contracts for each client or scenario.
  3. Forms and Applications: Many organizations require users to fill out forms or applications. With the PDF Generator API, developers can easily generate these forms on the fly, prefilling them with user data and providing a seamless user experience.

A great way to create PDF forms and non-fillable PDFs in mass is to fill out fillable PDF templates with data. With the help of the API, you may create high-quality PDF documents with your fillable form fields automatically filled with JSON, XML, or Excel data.


Advantages of Using a PDF Generator API


Using a PDF Generator API provides several advantages for developers:

  1. Time and Effort Savings: By automating the PDF generation process, developers can save a significant amount of time and effort. Generating PDFs through API eliminates the need for manual document creation, allowing developers to focus on other critical aspects of their projects.
  2. Consistency and Accuracy: With the API, PDF generation becomes consistent and accurate. The data provided for each document is automatically populated in the correct form fields, ensuring precision and avoiding errors that may occur during manual data entry.
  3. Scalability: The API allows for easy scalability, making it possible to generate a large number of PDF documents efficiently. This is particularly useful when dealing with high-volume scenarios, such as mass mailings or document generation, for a large user base.
  4. Flexibility and Customization: Developers have the flexibility to customize the PDF generation process according to their specific requirements. They can define formatting, layout, and styling options to match their branding guidelines or tailor the generated PDFs to specific user preferences.

For developers and tech-savvy individuals, PDF generation APIs provide a powerful way to generate PDFs programmatically. These APIS offer flexibility and customization options, enabling you to automate the process and integrate PDF generation into your applications or workflows.


Types of PDF Generation API

There are various types of PDF generation APIs available, each offering different features and functionalities. Here are some commonly used types of PDF generation APIs:

HTML to PDF Conversion APIs: These APIs allow developers to convert HTML content, including web pages or HTML templates, into PDF documents. These APIs typically support CSS styles, JavaScript execution, and other web-related features, enabling the conversion of dynamic and interactive web content into PDF format.

The PDF generation is slow. If customers/users download generated PDFs from your application, it may negatively impact the user experience.

Reporting and Data Visualization APIs: Reporting and data visualization APIs focus on generating PDF reports and charts from structured data sources. They often provide built-in functionalities for creating data-driven reports, such as connecting to databases, querying data, and generating visualizations that can be embedded in PDF documents. These APIs are particularly useful for generating business reports, dashboards, and analytics-related PDF documents.

The layout options they offer are limited, and they are only useful for generating simple PDFs.

Server-side PDF Generation APIs: These APIs enable PDF generation on the server side of web applications. Developers can use server-side programming languages like Java, Python, or PHP to interact with the API and generate professional-looking PDF documents dynamically. Server-side PDF generation APIs typically offer a wide range of features, including text formatting, image insertion, table creation, and support for various document elements.

The template-based server-side APIs are considered to be more elegant and provide business users with control over templates. The templates are easily modifiable, and new templates can be easily introduced.


EDocGen PDF Generation API


It is the best template-based API for the generation of dynamic PDF files. It supports a wide range of dynamic field types. You can generate both fillable and non-fillable PDF files with it.

Apart from PDF, you can generate other document formats, including Excel, PowerPoint, and Word. The simple REST API is flexible to support every document type and generation scenario across the enterprise.

Dynamic Field Types


It supports the dynamic content 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. The system does not require a separate template editor and allows business users to edit them in Word/PDF editors.

Text and tables

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




Images and QR Codes

Populate Base64, Image URLs, QR Codes, and 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, and conditional statements (if-else) for generating proposals, invoices, contracts, etc.

Data sources


The simple API allows you to generate them from various data sources.

Data

JSON, XML, Excel

Databases

MySQL, MSSQL, Oracle, MongoDB

CRM

Salesforce, Dynamics 365



The system enables the generated documents distribution through various channels including Email, e-sign, print, and cloud storage. It offers out-of-box integration services with various email and cloud storage providers.

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 the username and password to /login. Use this token for every API call.
  2. The 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 the 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 to save 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-prem servers to accommodate your specific performance and security needs. With the RESTful API, PDF generation becomes modular. Applications make a call to the API server and the API returns the desired output.

Generate Office and PDF 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#

Java Python PHPJavaScript
                           
package com.api.edocgen.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.api.edocgen.dto.DBParameters;
import com.api.edocgen.dto.DocumentResponse;
import com.api.edocgen.dto.OutputDto;
import com.api.edocgen.dto.OutputResultDto;
import com.api.edocgen.util.Utils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.UUID;
import javax.annotation.PostConstruct;
@Service
@Component
public class GenerateDocumentService {
    @Autowired
    private Utils utils;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoginService loginService;
    /*
     * Standard URLs
     */
    public static String baseURL = "https://app.edocgen.com/api/v1/";
    public static String urlBulkGenerate = "https://app.edocgen.com/api/v1/document/generate/bulk";
    public static String urlOutputEmail = "https://app.edocgen.com/api/v1/output/email";
    public static String urlQueryDocument = "https://app.edocgen.com/api/v1/document/?search_column=filename&search_value=";
    /*
     * User Configuration
     */
    public static String outputFilePath = "./";
    public static String pathFile = "JSON_Data.json";
    public static String TemplateFileName = "edocgen_v1_union.docx";
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    private HttpHeaders headers;
    @PostConstruct
    public void postdata() throws Exception {
        /*
         * 
         * Database Configiuration Settings
         */
        DBParameters dbParameters = new DBParameters();
        dbParameters.setDbLimit("100");
        dbParameters.setDbPassword("l8XuHH8Xax");
        dbParameters.setDbVendor("mysql");
        dbParameters.setDbUrl("jdbc:mysql://[email protected]:3306/sql6508014/sdtest");
        dbParameters.setDbQuery("select * from sdtest");
        /*
         * This program supports following methods:
         * 
         *  ## Single File Generation API's ####
         *  
         *  getDocByApi(String documentId, String outputFileName, String outputFormat)
         * 
         * 
         * ###### Bulk Files Generation API's  #####
         * 
         * getDocsByApi (TemplateId, OutputFormat)                          ====> This method generates bulk document based on JSON template which is present locally and downloads .zip file
         * getDocsByDatabase(TemplateId , OutputFormat , DBConfiguration)   ====> This method generates bulk document from database entries which is hosted in MySQL and downloads .zip file
         * 
         * ## Generic Method works both for single and Bulk #####
         * getTemplateId(TemplateFileName);                                 ====> This method returns templateid based on filename  
         * sendOutputViaEmail(TemplateId , Email)                           ====> This method sends generated output files directly to email via given templateID.
         */
        // String templateID =  getTemplateId(TemplateFileName);
        //getDocsByApi("62d95a226760033416374c10", "pdf");
         getDocsByDatabase("62bdaf8308bcc4761b6aa6b9", "pdf", dbParameters);
        // sendOutputViaEmail("62dfa645c2dae13e2ee6ec3e", "[email protected]");
       // getDocByApi("62bdaf8308bcc4761b6aa6b9", "SDTest", "pdf");
    }
    public void getDocByApi(String documentId, String outputFileName, String outputFormat) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        try {
            //convert file to byteArrayResource
            ByteArrayResource resource = getByteArrayResource();
            //create the body request
            MultiValueMap<String, Object> body = createBody(resource,documentId,outputFileName,outputFormat);
            //set Headers
             headers = Utils.getHttpHeaders(MediaType.APPLICATION_JSON,
                    MediaType.MULTIPART_FORM_DATA, Utils.apiToken);
                    headers.set("x-access-token", utils.apiToken);
            //send the request to generate document
            HttpEntity requestEntity = new HttpEntity(body, headers);
            ResponseEntity<String> generateResponse = restTemplate.postForEntity(urlBulkGenerate,
                    requestEntity, String.class);
                    String outputFile = outputFilePath + outputFileName + "." + outputFormat;
                    if (HttpStatus.OK == generateResponse.getStatusCode()) {
                        headers.clear();
                        headers.set("x-access-token", utils.apiToken);
                        requestEntity = new HttpEntity(null, headers);
                        ResponseEntity result = restTemplate.exchange(
                                baseURL + "output/name/" + outputFileName + "." + outputFormat , HttpMethod.GET,
                                requestEntity, OutputResultDto.class);
                        System.out.println("Send to edocGen Response : " + generateResponse.getStatusCode());
                        processOutput(result, outputFileName, outputFormat, requestEntity , true);
                    }
            //concat to outputPath the name of the file and the format
            //save the file
        } catch (Exception e) {
            System.out.print("Single File Generation Failed");
            System.out.println(e.getMessage());
        }
    }
    public String getTemplateId(String TemplateFileName) {
        String resourceUrl = urlQueryDocument
                + TemplateFileName;
        HttpHeaders headers = new HttpHeaders();
        headers.set("x-access-token", utils.apiToken);
        HttpEntity request = new HttpEntity(headers);
        // Fetch JSON response as String wrapped in ResponseEntity
        ResponseEntity response = restTemplate.exchange(resourceUrl, HttpMethod.GET, request,
                DocumentResponse.class);
        String templateId = response.getBody().getDocuments().get(0).get_id();
        System.out.println("Template id is : " + templateId);
        return templateId;
    }
    public void sendOutputViaEmail(String outId, String emailId) {
        RestTemplate restTemplate = new RestTemplate();
        try {
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("outId", outId);
            body.add("emailId", emailId);
            // set Headers
            headers = utils.getHttpHeaders(MediaType.APPLICATION_JSON,
                    MediaType.MULTIPART_FORM_DATA, utils.apiToken);
            // send the request to generate document
            HttpEntity requestEntity = new HttpEntity(body, headers);
            ResponseEntity<String> generateResponse = restTemplate.postForEntity(urlOutputEmail,
                    requestEntity, String.class);
            System.out.println("Send to edocGen Response : " + generateResponse.getStatusCode());
            if (HttpStatus.OK == generateResponse.getStatusCode()) {
                System.out.print("Email sent");
            }
        } catch (Exception e) {
            System.out.println("Exception During Sending Email. Check if document id is valid");
        }
    }
    public void getDocsByDatabase(String documentId, String outputFormat, DBParameters dbparmeters) throws Exception {
        String outputFileName = UUID.randomUUID().toString();
        try {
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("documentId", documentId);
            body.add("format", outputFormat);
            body.add("outputFileName", outputFileName);
            body.add("dbVendor", dbparmeters.getDbVendor());
            body.add("dbUrl", dbparmeters.getDbUrl());
            body.add("dbLimit", dbparmeters.getDbLimit());
            body.add("dbPassword", dbparmeters.getDbPassword());
            body.add("dbQuery", dbparmeters.getDbQuery());
            // set Headers
            headers = utils.getHttpHeaders(MediaType.APPLICATION_JSON,
                    MediaType.MULTIPART_FORM_DATA, utils.apiToken);
            // send the request to generate document
            HttpEntity requestEntity = new HttpEntity(body, headers);
            ResponseEntity<String> generateResponse = restTemplate.postForEntity(urlBulkGenerate,
                    requestEntity, String.class);
            System.out.println("Send to edocGen Response : " + generateResponse.getStatusCode());
            if (HttpStatus.OK == generateResponse.getStatusCode()) {
                headers.clear();
                headers.set("x-access-token", utils.apiToken);
                requestEntity = new HttpEntity(null, headers);
                ResponseEntity result = restTemplate.exchange(
                        baseURL + "output/name/" + outputFileName + "." + outputFormat + ".zip", HttpMethod.GET,
                        requestEntity, OutputResultDto.class);
                processOutput(result, outputFileName, outputFormat, requestEntity, false);
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
    private void processOutput(ResponseEntity result, String outputFileName, String outputFormat,
            HttpEntity requestEntity , boolean isSingleGeneration) {
        OutputDto responseOutput = null;
        if ( isSingleGeneration == false) {
            outputFormat = outputFormat + ".zip";
        }
        int retryCounter = 0;
        try {
            while (result.getBody().getOutput().toString().length() <= 2 && retryCounter < 200) {
                System.out.println(
                        "Output file is still not available. Retrying again!!!! Counter : " + retryCounter);
                result = restTemplate.exchange(
                        baseURL + "output/name/" + outputFileName + "." + outputFormat, HttpMethod.GET,
                        requestEntity, OutputResultDto.class);
                retryCounter++;
            }
            responseOutput = result.getBody().getOutput().get(0); // naam change kro
        } catch (IndexOutOfBoundsException error) {
            System.out.println("Error : Output file is not available after 200 tries");
        }
        System.out.println("Output Document Id generated at edocgen is : " + responseOutput.get_id());
        String outputId = responseOutput.get_id();
        // output download
        headers.clear();
        headers.set("x-access-token", utils.apiToken);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
        requestEntity = new HttpEntity(null, headers);
        ResponseEntity response = restTemplate.exchange(baseURL + "output/download/" + outputId,
                HttpMethod.GET, requestEntity, byte[].class);
        try {
            Files.write(Paths.get(outputFileName + "." + outputFormat), response.getBody());
            System.out.println("File downloaded from edocgen with name : " + outputFileName + "." + outputFormat);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.print("Error while Downloading File");
        }
    }
    public void getDocsByApi(String documentId, String outputFormat) throws Exception {
        String outputFileName = UUID.randomUUID().toString();
        try {
            // convert file to byteArrayResource
            ByteArrayResource resource = getByteArrayResource();
            // create the body request
            MultiValueMap<String, Object> body = createBody(resource, documentId, outputFileName, outputFormat);
            // set Headers
            headers = utils.getHttpHeaders(MediaType.APPLICATION_JSON,
                    MediaType.MULTIPART_FORM_DATA, utils.apiToken);
            // send the request to generate document
            HttpEntity requestEntity = new HttpEntity(body, headers);
            ResponseEntity<String> generateResponse = restTemplate.postForEntity(urlBulkGenerate,
                    requestEntity, String.class);
            if (HttpStatus.OK == generateResponse.getStatusCode()) {
                headers.clear();
                headers.set("x-access-token", utils.apiToken);
                requestEntity = new HttpEntity(null, headers);
                ResponseEntity result = restTemplate.exchange(
                        baseURL + "output/name/" + outputFileName + "." + outputFormat + ".zip", HttpMethod.GET,
                        requestEntity, OutputResultDto.class);
                System.out.println("Send to edocGen Response : " + generateResponse.getStatusCode());
                processOutput(result, outputFileName, outputFormat, requestEntity, false);
            } else {
                throw new HttpClientErrorException(generateResponse.getStatusCode());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    private MultiValueMap<String, Object> createBody(ByteArrayResource resource,
            String documentId, String outputFileName, String outPutFormat) {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("documentId", documentId);
        body.add("inputFile", resource);
        body.add("format", outPutFormat);
        body.add("outputFileName", outputFileName);
        // to download directly the file
        body.add("sync", true);
        return body;
    }
    private ByteArrayResource getByteArrayResource() throws IOException {
        String fileName = new File(pathFile).getName();
        Files.readAllBytes(Paths.get(pathFile));
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(pathFile))) {
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        return resource;
    }
}
              
                        
                          
import requests
import uuid
import os.path
import json
edocgen_dev = 'app.edocgen.com'
base_url = "https://%s" %(edocgen_dev)
url = "%s/login" %(base_url)
payload = "{\n\t\"username\":\"[email protected]\",\n\t\"password\": \"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/edocgen/Downloads/s1.docx"
files = {'documentFile': open(template_file,'rb')}
response = requests.post(url, files=files, headers=headers)
print(response, response.json())
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 = "pdf"
template_data = "/Users/edocgen/Downloads/s1.json"
inputData = []
with open(template_data, 'r') as content:
	inputData = json.load(content)
print(inputData)
# More than one input will always generate the zip file
inputValues = json.dumps({  
  'sync': True,
  'format': generated_format,
  'documentId': template_id,
  'outputFileName': outputFileName,
  'passwordColumn': 'Password',
  'markers': inputData 
})
outFormat = generated_format
if len(inputData) > 1:
	outFormat = 'zip'
headers['content-type'] = 'application/json'
print(url)
response = requests.post(url, data=inputValues, headers=headers, allow_redirects=False)
print(response)
download_to_file = "/Users/edocgen/Downloads/downloaded.%s" %(outFormat)
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())
              
                        
                          
<?php
require "restclient.php";
error_reporting(E_ALL & ~E_NOTICE);
class Edocgen
{
    private $api = "";
    private $results = "";
    private $response = "";
    function __construct()
    {
        // To get user specific token
        $ENV["EDOC_USERNAME"] = "[email protected]";          //edocgen username 
        $ENV["EDOC_PASSWORD"] = "";                 //edocgen password
        $this->api = new RestClient(["base_url" => "https://app.edocgen.com/"]);
        $this->result = $this->api->post("login", [
            "username" => $ENV["EDOC_USERNAME"],
            "password" => $ENV["EDOC_PASSWORD"],
        ]);
        $this->response = $this->result->decode_response();
        #   print_r($this->response);
    }
    public function downloadBulkUsingJson()
    {
        if ($this->result->info->http_code == 200) {
            /* 
            These variable need to be adjusted as per requirement:
            $format = "pdf";  // contains output format
            $downloadedFileExt = ".zip";    // download fileout output format. Incase of bulk this will be .zip always  
            $documentId = "62f063426844520f75344091";   // documentID or TemplateId of document 
            $MAX_RETRY = 50;  //Max number of retries to wait for download. Default 50.                             
            $jsonFilePath =  "/Users/Documents/TempWork/project/services/JSON_Data.json"; //path of json file to load 
            */
            // Start of customizing variables enter here
            $format = "pdf";
            $downloadedFileExt = ".zip";
            $documentId = "62f063426844520f75344091";
            $MAX_RETRY = 50;
            $jsonFilePath =  "/Users/JSON_Data.json";
            //End
            $curl = curl_init();
            $fileName = strtoupper(bin2hex(openssl_random_pseudo_bytes(16)));
            $key = $this->response->token;
            echo $key . "\n";
           // echo $fileName . "\n";
            $data = [
                "inputFile" => new CURLFILE(
                    $jsonFilePath 
                ),
                "documentId" => $documentId,
                "format" => "pdf",
                "outputFileName" => $fileName,
            ];
            $inp = [
                CURLOPT_URL => "https://app.edocgen.com/api/v1/document/generate/bulk",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_HTTPHEADER => ["x-access-token: $key"],
            ];
            curl_setopt_array($curl, $inp);
            $response = curl_exec($curl);
            curl_close($curl);
            echo $response;
            if ($response === false) {
                print "Could not make successful request\n";
                return;
            } else {
                $response = json_decode($response);
            }
            $arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
            $retry = 0;
            while (
                is_null($arr["output"][0]["_id"]) != null &&
                $retry < $MAX_RETRY
            ) {
                echo 'Retrying Again.... \n';
                echo $retry;
                $arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
                $retry++;
            }
            if (is_null($arr["output"][0]["_id"])) {
                echo 'Error !!! Cannot generate output after serveral retries \n';
                return "";
            } else {
                $output_id = $arr["output"][0]["_id"];
                $this->downloadOutput($output_id, $fileName, $downloadedFileExt);
            }
        }
    }
    public function downloadSingleUsingJson()
    {
        if ($this->result->info->http_code == 200) {
            /* 
            These variable need to be adjusted as per requirement:
            $format = "pdf";  // contains output format
            $downloadedFileExt = ".zip";    // download fileout output format. Incase of bulk this will be .zip always  
            $documentId = "62f063426844520f75344091";   // documentID or TemplateId of document 
            $MAX_RETRY = 50;  //Max number of retries to wait for download. Default 50.                             
            $jsonFilePath =  "/Users/Documents/TempWork/project/services/JSON_Data.json"; //path of json file to load 
            */
            // Start of customizing variables --- enter here
            $downloadedFileExt = "pdf";
            $documentId = "62f063426844520f75344091";
            $MAX_RETRY = 50;
            $jsonFilePath =  "/Users/JSON_Data_Single.json";
            //End
            $curl = curl_init();
            $fileName = strtoupper(bin2hex(openssl_random_pseudo_bytes(16)));
            $key = $this->response->token;
            echo $key . "\n";
           // echo $fileName . "\n";
            $data = [
                "inputFile" => new CURLFILE(
                    $jsonFilePath 
                ),
                "documentId" => $documentId,
                "format" => "pdf",
                "outputFileName" => $fileName,
            ];
            $inp = [
                CURLOPT_URL => "https://app.edocgen.com/api/v1/document/generate/bulk",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_HTTPHEADER => ["x-access-token: $key"],
            ];
            curl_setopt_array($curl, $inp);
            $response = curl_exec($curl);
            curl_close($curl);
            echo $response;
            if ($response === false) {
                print "Could not make successful request\n";
                return;
            } else {
                $response = json_decode($response);
            }
            $arr = $this->checkOutputGenerated($fileName, "", $downloadedFileExt);
            $retry = 0;
            while (
                is_null($arr["output"][0]["_id"]) != null &&
                $retry < $MAX_RETRY
            ) {
                echo 'Retrying Again.... \n';
                echo $retry;
                $arr = $this->checkOutputGenerated($fileName, "", $downloadedFileExt);
                $retry++;
            }
            if (is_null($arr["output"][0]["_id"])) {
                echo 'Error !!! Cannot generate output after serveral retries \n';
                return "";
            } else {
                $output_id = $arr["output"][0]["_id"];
                $this->downloadOutput($output_id, $fileName, ".".$downloadedFileExt);
            }
        }
    }
    public function downloadBulkUsingDB()
    {
        if ($this->result->info->http_code == 200) {
            /*
            These variable need to be adjusted as per requirement:
            $format = "pdf";                     //output format of document generated in edocgen   
            $dbUrl ="jdbc:mysql://[email protected]:3306/sql6511576/sdtest"; // MySQL DB URL
            $dbPassword = "u8M7IYAq7a";             //db password
            $dbQuery = "select * from sdtest";      //db query
            $dbLimit = "100";                       //Number of db entries to be fetched
            $zip = ".zip";                          //Downloaded file format. bydefault only .zip is supported     
            $MAX_RETRY = 50;                        //Max number of tries to download file from edocgen
            $documentId = "62f063426844520f75344091";   //Template id from edocgen
            */
            // Start of customizing variables
            $format = "pdf";
            $dbVendor = "mysql";
            $dbUrl ="jdbc:mysql://[email protected]:3306/sql6511576/sdtest";
            $dbPassword = "u8M7IYAq7a";
            $dbQuery = "select * from sdtest";
            $dbLimit = "100";
            $downloadedFileExt = ".zip";
            $MAX_RETRY = 50;
            $documentId = "62f063426844520f75344091";
            // end of variables
            $curl = curl_init();
            $fileName = strtoupper(bin2hex(openssl_random_pseudo_bytes(16)));
            $key = $this->response->token;
            echo $key . "\n";
            echo $fileName . "\n";
            $data = [
                "dbVendor" => $dbVendor,
                "dbUrl" => $dbUrl,
                "dbLimit" => $dbLimit,
                "dbPassword" => $dbPassword,
                "dbQuery" => $dbQuery,
                "documentId" => $documentId,
                "format" => $format,
                "outputFileName" => $fileName,
            ];
            $inp = [
                CURLOPT_URL => "https://app.edocgen.com/api/v1/document/generate/bulk",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_HTTPHEADER => ["x-access-token: $key"],
            ];
            curl_setopt_array($curl, $inp);
            $response = curl_exec($curl);
            curl_close($curl);
            echo $response;
            if ($response === false) {
                print "Could not make successful request\n";
                return;
            } else {
                $response = json_decode($response);
            }
            $arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
            $retry = 0;
            while (
                is_null($arr["output"][0]["_id"]) != null &&
                $retry < $MAX_RETRY
            ) {
                echo 'Retrying Again.... \n';
                echo $retry;
                $arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
                $retry++;
            }
            if (is_null($arr["output"][0]["_id"])) {
                echo 'Error !!! Cannot generate output after serveral retries \n';
                return "";
            } else {
                $output_id = $arr["output"][0]["_id"];
                $this->downloadOutput($output_id, $fileName, $downloadedFileExt);
            }
        }
    }
    public function sendOutputToEmail($outputId, $emailId)
    {
        $curl = curl_init();
        $key = $this->response->token;
        $data = [
            "outId" => $outputId,
            "emailId" => $emailId,
        ];
        $postdata = json_encode($data);
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://app.edocgen.com/api/v1/output/email",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postdata,
            CURLOPT_HTTPHEADER => [
                "x-access-token: $key",
                "Content-Type: application/json",
            ],
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        print_r($response);
    }
    //Utility Function to download outputID
    public function downloadOutput($outputId, $fileName, $downloadedFileExt)
    {
        $curl = curl_init();
        $key = $this->response->token;
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://app.edocgen.com/api/v1/output/download/" . $outputId,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => ["x-access-token: $key"],
        ]);
        $raw_file_data = curl_exec($curl);
        curl_close($curl);
        echo "File Downloaded with name " .
        $fileName.                 
        $downloadedFileExt."\n";
            file_put_contents(
                "./".$fileName.$downloadedFileExt,                  
                $raw_file_data
            );
    }
    public function getTemplateIdviaFileName($fileName)
    {
        if ($this->result->info->http_code == 200) {
            $curl = curl_init();
            $key = $this->response->token;
            curl_setopt_array($curl, [
                CURLOPT_URL =>
                    "https://app.edocgen.com/api/v1/document/?search_column=filename&search_value=" .
                    rawurlencode($fileName),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_HTTPHEADER => ["x-access-token: $key"],
            ]);
            $response = curl_exec($curl);
            curl_close($curl);
            $arr = json_decode($response, true);
            echo "Template ID's with file name - $fileName is : \n";
            foreach ($arr["documents"] as $key => $value) {
                print_r($value["_id"]);
                echo "\n";
            }
        }
    }
    //Utility function to check and download output generated in edocGen
    public function checkOutputGenerated($fileName, $format, $downloadedFileExt)
    {
        $curl = curl_init();
        $key = $this->response->token;
        if ($format == "") {
            $uri = $downloadedFileExt;
        }
        else{
            $uri = $format.$downloadedFileExt;
        }
        echo "Checking Output Generated at: " .
            "https://app.edocgen.com/api/v1/output/name/" .
            $fileName.
            "." .
            $uri.
            "\n";
        curl_setopt_array($curl, [
            CURLOPT_URL =>
                "https://app.edocgen.com/api/v1/output/name/" .
                $fileName.
                "." .
                $uri,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => ["x-access-token: $key"],
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        $arr = json_decode($response, true);
        //  echo print_r(json_decode($response, true));
    //    print_r($arr);
        return $arr;
    }
}
$a = new Edocgen();
//$a->downloadBulkUsingJson();
//$a->downloadSingleUsingJson();
//$a->downloadBulkUsingDB();
//$a->getTemplateIdviaFileName("EDocGen_Testing Invoice.docx");
//$a->sendOutputToEmail("62dac1177b5ea11abd3ba38a", "[email protected]");
?>
            
                        
                          
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 = "pdf";
const documentId = "62bed474447071367d4b1e31";    // Add the template id here
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);
    formBody.append("inputFile", fs.createReadStream("./JSON_Data.json"));
    let config = {
      method: "post",
      url: hostName,
      headers: headers,
      data: formBody,
    };
    console.log(
      `https://app.edocgen.com/api/v1/output/name/${fileName}` +
        "." +
        outputFormat +
        ".zip"
    );
    let config_output = {
      method: "get",
      url:
        `https://app.edocgen.com/api/v1/output/name/${fileName}` +
        "." +
        outputFormat +
        ".zip",
      headers: headers,
    };
    const MAX_RETRY = 50;
    let currentRetry = 0;
    function errorHandler() {
      if (currentRetry < MAX_RETRY) {
        currentRetry++;
        console.log(
          "Output files are not generated at edocgen yet! Retrying..."
        );
        sendWithRetry(processResponse);
      } else {
        console.log("Retried several times but still failed");
      }
    }
    function sendWithRetry(callback) {
      axios(config_output)
        .then(function (response) {
          if (response.data.output.length !== 1) {
            throw new axios.Cancel("Operation canceled by the user.");
          } 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(
    "Edocgen Output Document Generated with 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",
    accept: "application/zip",
  };
  axios(config_download)
    .then(function (response) {
      console.log("Output file is downloaded with " + `${fileName}.zip`);
      fs.writeFileSync(`./${fileName}.zip`, response.data);
    })
    .catch(function (error) {
      console.log("Error while downloading");
      console.log(error);
    });
}

                        


Frequently Asked Questions


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

Yes, you can generate password-protected complex PDF documents with watermarks. The instructions for opening the PDF can be sent to the user via email along with the attachment. Additionally, the system compresses the PDF to reduce the file size, enabling faster download speeds.

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, utilizing the powerful PDF generation API.

Do you support PDF form generation?

Yes. You can generate both fillable and non-fillable PDF documents with the API.

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 AWS S3, OneDrive, or SharePoint DMS.
  4. Send them for e-sign.
  5. Create print-ready documents in PDF, PCL5, or PostScript format.

Popular Posts