Contract Generation Software

Salesforce document generation - PDF and Office docs

Overview

EDocGen is an efficient template-based document generation tool that empowers users to create automated documents with ease. By utilizing pre-built templates, businesses can quickly generate documents in various formats, including PDF, Microsoft Word, PowerPoint, and more. The ability to generate documents in bulk or one at a time adds to the versatility of the platform, making it a reliable solution for companies of all sizes.

Salesforce is a widely adopted CRM platform that helps organizations manage their customer relationships effectively. EDocGen provides seamless integration with Salesforce, allowing users to leverage their existing workflows and effortlessly incorporate template-based automatic document generation into their processes. By taking advantage of this integration, businesses can enhance their document automation capabilities and leverage the power of automation within the CRM environment.

Integration Details

Prerequisites

  • Salesforce Account: To integrate the document generation solution with Salesforce, you need to have an active Salesforce account and administrator access or permission to install and configure third-party applications in Salesforce.
  • Enabling Salesforce OAuth Access :

Before you can access Salesforce from the system environment, you need to ensure that you have created a Connected App within Salesforce to obtain the required credentials for OAuth authentication.

To enable Salesforce OAuth access

  1. Log in to your Salesforce account as a Salesforce administrator.
  2. Navigate to the Salesforce Setup page.
  3. In the left-hand sidebar, under the "Platform Tools" section, click on "Apps" and then select "App Manager".
  4. Click on the "New Connected App" button to create a new Connected App.
  5. Provide a name for your Connected App and fill in other required details.
  6. Check the "Enable OAuth Settings" checkbox.
  7. Enter the Callback URL.
  8. Choose the below scopes:
    1. Manage your data (api)
    2. Full access (full)
    3. Perform requests on your behalf at any time (refresh_token, offline_access)
  9. Save the Connected App settings.

Salesforce OAuth Configuration

With the Salesforce OAuth access enabled and the Connected App created you are now ready to authenticate and access the Salesforce API using OAuth authentication. The obtained credentials will be used during the authentication process to obtain an access token.

  • Salesforce API Access: Ensure that your Salesforce account has API access enabled. This is required to establish a connection between Salesforce and document generation software, allowing data transfer for document generation.

To enable API access for external users in Salesforce, follow these steps:

  1. Access User Profiles: In the left sidebar of the Setup page, under "Administrator," expand the "Manage Users" section and click on "Profiles."
  2. Edit Profile: Locate and select the profile associated with the external users who require API access. Click on the profile name to open the profile settings.
  3. Enable API Access: Within the profile settings, scroll down to the "Administrative Permissions" section. Check the box that says "API Enabled" to enable API access for the selected profile.
  4. Define API Rights: In the same profile settings, scroll further to the "Object Permissions" section. Here, you can specify the API rights for the external users. Choose the appropriate access levels (e.g., read, write, delete) for specific objects and fields based on your requirements.
  5. Save Changes: After configuring the API access and permissions for the profile, click on the "Save" button to save your changes.

EDocGen is an API-first product and offers a variety of modes of document generation, including on-demand and bulk. Thus, it can be used by both business users and developers. It also offers integration with various enterprise systems and databases, making it adaptable to a wide range of use cases within an enterprise.

In the following sections, we will provide a step-by-step guide for how to generate documents from product UI and API.

Generation from User Interface

Authentication

The first step is to authenticate your Salesforce account from the system UI.

  1. Click on integrations on the left nav.
  2. Clicking on the "Authenticate" button takes you to the Salesforce login. page.
  3. After successful login, you notice the button name changes from "Authenticate" to "Remove". You can remove the authentication at any time.
Salesforce edocgen authentication

Steps for Generation

Upload Template

Step1: Upload your template

The system offers versatility by supporting various document template formats, including PDF, PPTX, and DOCX, allowing users to choose the format that best suits their needs.

Business users can use existing templates as-is. They only need to add dynamic data placeholders in their templates. The tags such as {Enter_Name} and {Enter_Email} can be used to represent dynamic data that will be replaced with actual values from Salesforce during document generation.

Step 2: Click the "Generate" button against the template and select "CRM input".

Salesforce edocgen authentication

Step 3: Select Salesforce from the drop-down list and enter the URL.


Salesforce edocgen authentication

There are different ways to query data using URLs in the Salesforce API, and the provided examples demonstrate two common approaches:

Querying Data:

URL: https://t-dev-ed.develop.my.salesforce.com/services/data/v51.0/query?q=SELECT+Id,Name+FROM+Account&Limit=2

This URL utilizes the Salesforce REST API's query endpoint to retrieve data from the Account object. The query string parameter q specifies the SELECT statement (SELECT Id, Name FROM Account) to fetch the Id and Name fields from the Account object. Additionally, the Limit=2 parameter limits the result to two records. This URL retrieves a set of records that match the given query criteria.

Retrieving Data by Record ID:

URL: https://t-dev-ed.develop.my.salesforce.com/services/data/v51.0/sobjects/Account/0015i00000dkhDQAAY

This URL is used to fetch a specific record from the Account object using its unique ID. The URL path starts with /sobjects/Account , indicating the Salesforce object type, followed by the record ID (0015i00000dkhDQAAY). This URL retrieves the detailed information of a single record identified by its unique ID.

By modifying the URL structure and query parameters, you can perform various types of data retrieval operations, such as querying multiple records based on specific criteria or fetching individual records by their unique identifiers.

Step 4: Click the "Finish" button to generate PDF, DOCX, and PPTX files.

Sales teams can use this approach for response documents, contracts, and complex documents creation as part of the sales cycle.


Generation using API

Authentication

The API uses a JWT-based authentication token to secure all API interactions. To obtain this token, you must first register and submit your login credentials to the /login endpoint. Once you have successfully registered, you will be provided with an access token. This token must be included in every subsequent API call.

Here is a more detailed explanation of the authentication process:

  1. Register with the API by submitting your username and password to the /login endpoint.
  2. The API will return an access token.
  3. Include the access token in every subsequent API call.

The access token is a secure, unique identifier that allows the API to authenticate your requests. It is important to keep your access token safe and secure. If you lose your access token, you will need to register for a new one.

```createtoken.js````


async function createToken(username, password) {
  const url = 'https://app.edocgen.com/login';
  const headers = {
    'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
    'Content-Type': 'application/json',
    'accept': 'application/json'
  };
  const body = {
    username: username,
    password: password
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body)
    });

    if (!response.ok) {
      throw new Error(`Failed to create token: ${response.statusText}`);
    }

    const data = await response.json();
    return data.token;
  } catch (error) {
    console.error(error);
    throw new Error(`Failed to create token: ${error.message}`);
  }
}

module.exports = createToken;

```

Upload the Template

After creating the template, it can be uploaded using either from UI or API.

It provides the following API, which can be used to upload the template file to the system server.

POST

/api/v1/document

Upload template

documentFile *

file (formData)

 

File to upload

 

x-access-token

string (header)

Authorization header obtained by calling login



This API accepts a single parameter of type "formData" called "documentFile". This parameter represents the file to be uploaded as the template.

Retrieve Template ID

After uploading our template to the server, we can obtain the corresponding template ID. This ID can be utilized to execute different API functions related to that specific template.

The API offers the capability to retrieve the template ID.

Method

Endpoint

Description

GET

/api/v1/document

 

Returns template details

 

 

In Javascript, we can do this using the following method:

```


const axios = require("axios");

const hostName = "https://app.edocgen.com/api/v1/document/?search_column=filename&search_value=";
const headers = {
  "Content-Type": "application/json",
  "x-access-token": “”,
};

const fileName = "EDocGen_Testing Invoice.docx"; 

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

    let config = {
      method: "get",
      url: hostName + fileName,
      headers: headers,
    };

    axios(config)
      .then(function (response) {
        console.log("Template IDs for the documents are as follows:");
        let data = response.data.documents;
        data.forEach((element) => {
          console.log("Here -> " + element._id);
        });
        console.log();
      })
      .catch(function (error) {
        console.log(error);
      });
  });
};
    

```

Generate Documents

Once we have template Id, the next step is to generate documents.

The system enables the merging of the fetched data into the template's designated placeholders or dynamic fields. This process ensures that the generated documents are populated with the relevant information sourced from Salesforce CRM.


const createToken = require('./createtoken.js');
const axios = require('axios');
const fs = require("fs");
const dotenv = require('dotenv');




dotenv.config({
  path: './userparams.env'
});


const timestamp = new Date().toISOString().replace(/[-:.TZ]/g, '');
const randomString = Math.random().toString(36).substring(2, 8);
var fileExtension;




async function processData(data) {
  const formData = new FormData();
  const token = await createToken(process.env.EDOCGEN_USERNAME, process.env.EDOCGEN_PASSWORD);
  const headers = new Headers();


  console.log(" \n *****Processing data starts***");


  if (Array.isArray(data)) {
    fileExtension = '.zip';
  } else {
    fileExtension = '.pdf';
  }


  var filename = `${timestamp}-${randomString}` + fileExtension;
  const jsonBlob = new Blob([JSON.stringify(data)], {
    type: 'application/json'
  });


  console.log(`Token: ${token}`);


  headers.append('x-access-token', token);
  formData.append('documentId', process.env.DOCUMENT_ID);
  formData.append('format', process.env.FORMAT);
  formData.append('outputFileName', filename);
  formData.append('crm', “salesforce”);
  formData.append('reqOrigin', 'https://app.edocgen.com’);
  formData.append('hostUrl', 'https://s-dev-ed.develop.my.salesforce.com/services/data/v51.0/query?q=SELECT%20Id,Name%20FROM%20Account&Limit=2’);


  fetch('https://app.edocgen.com/api/v1/generate/bulk', {
    method: 'POST',
    headers: headers,
    body: formData
  })
    .then(response => response.json())
    .then(data => {
      console.log(data);
      // Call the checkOutputFile function here
      async function downloadFile() {
        const outputId = await checkOutputFile(filename, maxAttempts = 10, token);
        downloadOutput(outputId, token, filename);
      }


      downloadFile();


    })
    .catch(error => console.error(error));


}

async function downloadOutput(outputId, token, fileName) {


  console.log(
    "Edocgen Output Document Generated with Id -",
    outputId
  );


  const headers = {
    "x-access-token": token
  };


  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}`);
      fs.writeFileSync(`./${fileName}`, response.data);
    })
    .catch(function (error) {
      console.log("Error while downloading");
      console.log(error);
    });




  if (process.env.EDOCGEN_OUTPUT_SEND_EMAIL == "YES") {
    sendEmail(outputId, process.env.EDOCGEN_OUTPUT_SENDER_EMAIL, token)
  }
}


async function checkOutputFile(fileName, maxAttempts, token) {
  console.log("Checking output file name --", fileName);
  const headers = {
    "Content-Type": "application/json",
    "x-access-token": token
  };


  const options = {
    method: "GET",
    headers: headers
  };


  for (let i = 1; i <= maxAttempts; i++) {
    const response = await fetch(`https://app.edocgen.com/api/v1/output/name/${fileName}`, options);
    const data = await response.json();
    console.log("File Generation Response -- Checking if output is generated by edocgen", data);


    if (data.output && data.output.length > 0) {
      const outputFile = data.output[0];
      return outputFile._id;
    }


    await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before retrying
  }


  throw new Error(`Output file "${fileName}" not generated after ${maxAttempts} attempts`);
}

    

```

In the provided code, the parameter responsible for fetching data is the hostUrlparameter. This parameter is used to specify the Salesforce URL endpoint from which data is retrieved.

For example,

```

formData.append('hostUrl', 'https://s-dev-ed.develop.my.salesforce.com/services/data/v51.0/query?q=SELECT%20Id,Name%20FROM%20Account&Limit=2 ’)

```

Once the output file is generated, the function calls the downloadOutput() method to download the file to the local file system. This method sends a GET request to the document generation solution API's /api/v1/output/download/{output_id} endpoint to download the file with the given output ID. The downloaded file is saved to the local file system with a name based on the generated file UUID to ensure uniqueness.

Send Output to Email

By leveraging the email delivery capabilities of the system, you can automate the process of sending the generated documents to the intended recipients. This ensures efficient and timely distribution of the documents, streamlining your document management and communication processes.

```


async function sendEmail(outputId, toEmail, token) {
  const url = 'https://app.edocgen.com/api/v1/output/email';

  const payload = {
    outId: outputId,
    emailId: toEmail,
  };

  const headers = {
    'Content-Type': 'application/json',
    'x-access-token': token
  };

  const response = await fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(payload)
  });

  const responseData = await response.json();
  console.log(responseData)
  if (response.ok) {
    console.log('Email sent successfully.');
  } else {
    console.error(`Failed to send email: ${responseData.message}`);
  }
}
    
```

Conclusion

In conclusion, EDocGen document generation software offers a powerful and versatile solution for automating document generation. By streamlining workflows, reducing errors, and providing features such as multi-format generation and email delivery, it empowers businesses to save time, enhance accuracy, and boost productivity. With its automation capabilities, it is an essential tool for optimizing document generation processes and driving efficiency in any organization.

Popular Posts

.