Contract Generation Software

How to Generate PDF and Office Documents in Dynamics 365

Overview

Dynamics 365 is a widely adopted CRM platform that helps organizations effectively manage their customer relationships. EDocGen seamlessly integrates with Dynamics 365, allowing users to leverage their existing workflows and effortlessly incorporate template-based complex document generation into their processes. Businesses can enhance their document generation capabilities and leverage the power of automation within the CRM environment.

Whether you're new to automation or just looking to optimize your current process, EDocGen allows you to create templates and automate workflows for generating PDFs and Office documents in Dynamics 365.

Keep reading to know how!

How Document Generation Works in Dynamics 365

Dynamics 365 document generation relies on tools like Word templates and Mail merge, but these often need to be revised for complex or high-volume tasks. 

EDocGen enhances these capabilities by providing:

  • Integration with Dynamics 365 data entities.

  • Support for PDF, DOCX, PPTX, and Excel formats.

  • Advanced templates with conditional logic and nested data.

  • Batch processing for large-scale document automation.

Here’s how different teams use these features:

Department

Functionality

Sales

Create proposals and quotes quickly from data.

Legal

Generate contracts with pre-filled terms.

Finance

Automate invoices and financial reports.

HR

Prepare offer letters and employee contracts.

Compliance

Produce accurate regulatory documents.

It’s evident how automation transforms manual tasks into faster, more reliable workflows. Before moving forward, ensure your system is ready with proper authentication and prerequisites.

Preparing For Integration With EDocGen

To get started with EDocGen integration, you'll need to ensure your system meets these technical prerequisites:

  • Microsoft Dynamics 365 Subscription: Must be active with administrative access.

  • Supported Version: Dynamics 365 version 9.0.

  • Azure Active Directory (Azure AD): Required for OAuth setup.

  • EDocGen Subscription: API-enabled for seamless interaction.

Once you've confirmed these requirements, the next step is setting up OAuth authentication, a key element for secure integration.

OAuth Authentication

OAuth is a secure system that lets Dynamics 365 safely connect with tools like EDocGen, ensuring only authorized access to sensitive data.

Steps to Configure OAuth in Azure AD:

Register EDocGen
Add it as an enterprise application in Azure AD.

Set API Permissions
Assign and grant necessary permissions.

Generate Client Credentials

Obtain and securely store access tokens.

Once OAuth is configured, you're ready to design and manage templates.

Template Creation and Management

Templates form the backbone of your document generation process. 

Before starting with template design, let’s discuss the formats available and how they align with your business needs and specific document requirements.

EDocGen supports three major template formats:

Format

Key Features

Best For

Microsoft Word (DOCX)

  1. Dynamic content, tables, and images

  2. Complex formatting and styles

Contracts, proposals, text-heavy documents

PDF

  1. Consistent formatting

  2. Digital signatures and password protection

Finalized documents, secured forms

PowerPoint (PPTX)

  1. Charts and graphs

  2. Maintains brand consistency across slides

Presentations, visual reports

Once you’ve identified the format, the next step is designing templates that make the most of these features.

How to Create Effective Templates

  • Adhere to Brand Standards

Begin with a standard layout that reflects your organization's branding.

  • Use Dynamic Placeholders

Insert placeholders using EDocGen's syntax for seamless integration with Dynamics 365 fields.

  • Apply Conditional Logic

Set rules for content that varies based on data, ensuring flexibility.

  • Map Data Correctly

Ensure proper data mapping for related entities to avoid errors during document generation.

  • Test Before Deployment

Run tests with sample data to validate formatting, placeholders, and conditional logic.

Setting Up Authentication & Generating Documents

Secure authentication and flexible document generation are critical for efficient workflows in Dynamics 365. 

Depending on your organization's needs, you can choose between UI-based and API-based methods for authentication and document generation. 

Here’s a quick comparison to help you decide:

Aspect

User Interface (UI)

API-Based Approach

Purpose

Manual document generation

Automated document generation

Ideal For

Business users with no technical expertise

Developers and system integrators

Setup Requirements

Azure AD credentials and permissions

Client credentials for token generation

Steps

Step-by-step template and output selection

REST endpoints, token refresh, and error handling

Document Generation via User Interface (UI)

Authentication Steps:

  1. Navigate to EDocGen Settings

Access the EDocGen integration settings in your Dynamics 365 application.

  1. Select Azure AD Authentication

Choose the Azure Active Directory (AD) authentication method for secure access.

  1. Provide Credentials

Enter the required admin credentials and grant necessary permissions for the application.

  1. Validate Connection

Generate a test document to confirm that the authentication is working correctly.

Document Generation Steps:


Step 1 - Select Template:

Access the EDocGen interface and pick a template.

Step 2 - Choose Records:

Select Dynamics 365 records or entities to use for document generation.

Step 3 - Configure Settings:

Set output format (PDF, DOCX, etc.) and other options.

Step 4 - Generate Documents:

Initiate the process and retrieve the generated documents.

Document Generation via API

Authentication Steps:

  1. Obtain a JWT Token:

    • Register with the API by submitting your login credentials (username and password) to the /login endpoint.

    • The API will return a JWT-based access token upon successful login.

  2. Include Token in API Requests:

    • Use the received token as a header (Authorization: Bearer <token>).

    • Ensure the token is securely stored and refreshed periodically to maintain access.

  3. Secure Your Token:

    • Never expose tokens in client-side code.

    • Use secure methods to refresh and rotate tokens periodically.

```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;

```


Document Generation Steps:

Step 1 -  Upload the Template :

  • Use the /api/v1/document endpoint to upload your template.

  • Submit the template file as a formData parameter (documentFile).

POST

/api/v1/document

Upload Template

documentFile *

file (formData)

File to upload

x-access-token

string (header)

Authorization header obtained by calling login

Step 2 - Retrieve Template ID:

  • Once uploaded, retrieve the unique Template ID using the provided endpoint. This ID will be used for subsequent operations.

  • Use filtering parameters if managing multiple templates.


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);

      });

  });

};


```

Step 3 - Generate Documents:

  • Use the template ID to merge data into placeholders for document generation.

  • Specify the desired output format (PDF, DOCX, etc.) and data source (hostUrl parameter for Dynamics 365).

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', “dynamics365”);

  formData.append('reqOrigin', 'https://app.edocgen.com’);

  formData.append('hostUrl', 'https://org185d95f2.crm8.dynamics.com/api/data/v9.0/accounts’);



  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`);

}



    


```


Step 4 - Download the Generated Documents:

  • Access the /api/v1/output/download/{output_id} endpoint to download the generated document.

  • Files are saved with unique identifiers for version control.

Step 5 - Send Documents Via Email:


  • Automate the email distribution using the /api/v1/email/send endpoint.

  • Attach generated documents, define recipient lists, and track delivery status.



```


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}`);

  }

}

Data Integration: Retrieval and Mapping

Getting data from Dynamics 365 and mapping it to your templates is the cornerstone of successful document automation. 

This section guides you through key steps to integrate data seamlessly, minimize errors, and optimize your workflow.

REST Endpoint Usage

REST Endpoints provide robust data access capabilities, enabling precise data retrieval for various needs. 

You can use REST endpoints in the following ways:

  • OData Endpoints

Retrieve standard entity data effortlessly.

  • Custom FetchXML Queries

Handle complex or nested data requirements with flexibility.

  • Related Entity Navigation

Access associated records through navigation properties.

  • Filtered Queries

Apply filters to fetch specific datasets, reducing unnecessary data retrieval.


You can retrieve the needed data using these capabilities, ensuring accurate and efficient document generation.

We’ve broken down the process into two easy steps: 

Step 1: Retrieving Data from Dynamics 365

Choose Retrieval Method

  • Use OData Endpoints for standard entity data retrieval.

  • Opt for FetchXML Queries for more complex data needs.

Apply Filters

  • Utilize filtering parameters to target specific records and reduce unnecessary data retrieval.

Navigate Related Data

  • Leverage navigation properties to fetch data from related entities, ensuring all required information is included.

Step 2: Mapping Dynamics 365 Data to Templates

Define Field Relationships

  • Align Dynamics 365 fields with placeholders in the template for accurate data population.

Handle Data Conversions

  • Ensure compatibility by mapping field types from Dynamics 365 to template-ready formats.

Process Related Records

  • Integrate data from related entities into appropriate sections of the document.

Account for Empty Fields

  • Set up fallback values or default content to handle null or missing data gracefully.

Advanced Features

EDocGen extends beyond basic document generation, offering advanced capabilities to streamline workflows and enhance efficiency. 

Here’s an overview of its top features:

Automated Email Delivery

Effortlessly distribute documents with automated email functionality. This feature enables you to:

  • Use dynamic email templates tailored to recipient data.

  • Set recipient rules based on Dynamics 365 data fields.

  • Schedule automated triggers for delivery.

  • Track delivery success rates and engagement metrics.

Print-Ready Output

Prepare digital documents for professional printing with ease. With EDocGen, you can:

  1. Convert generated files into formats like PCL5 or PostScript.

  2. Customize paper sizes and printing specifications.

  3. Manage bulk print jobs efficiently.

Bulk Processing

Scale your document generation for high-volume needs:

  • Configure batch parameters for processing large datasets.

  • Monitor document processing status and handle retries for errors.

  • Generate logs and reports for improved monitoring.

Once you’ve leveraged these advanced features, optimizing your templates and integrations is key to achieving peak performance.

Optimizing the Process

As your document generation needs grow, focus on optimizing your templates and troubleshooting integration challenges. 

Here’s how:

Optimization Tip

Why It’s Important

Standardized styles

Ensures consistency across documents.

Modular components

Simplifies updates and customization.

Optimize file sizes

Speeds up processing and output times.

Version control

Tracks edits and prevents errors.

Integration Troubleshooting

You can resolve common issues quickly to avoid issues such as:

  • Authentication Errors

Ensure tokens are valid and permissions are set correctly.

  • Data Mapping Challenges

Double-check field mappings for accuracy.

  • Performance Issues

Monitor API response times and system load.

  • Error Logs

Regularly review error logs to identify recurring issues.

Conclusion

Automation isn’t optional anymore. With countless benefits ranging from savings to improved accuracy, implementing document generation automation with EDocGen and Dynamics 365 feels like a natural next step for any organization striving for efficiency.

In fact, many of our users who embraced automation for Dynamics 365 PDF generation experienced:

  • Up to 80% reduction in document creation time

  • Improved accuracy and consistency across workflows

  • Enhanced compliance and security standards

  • Scalable capabilities for high-volume document generation

Still wondering if this is the right fit for your organization? Here’s a quick checklist to help you decide:

  • Do you struggle with manual document workflows?

  • Are errors in your documents causing delays?

  • Do you need scalable document solutions?

If you answered "yes" to any of these, it’s time to take the next step.

To begin your implementation journey:

  1. Assess your current document generation needs.

  2. Review your Dynamics 365 environment requirements.

  3. Plan a comprehensive template strategy.

  4. Start with a pilot project to demonstrate ROI.

  5. Scale the solution across your organization.

Frequently Asked Questions

  1. What versions of Microsoft Word are supported for template creation?  

EDocGen supports Microsoft Word templates created in Word 2013 and newer versions, with the best compatibility in Microsoft 365.

  1. What is the maximum number of related records that can be included in a template? 

EDocGen allows unlimited related records in templates. 

Implementing pagination or batch processing is recommended to maintain optimal performance for large datasets and documents with over 1,000 records.

  1. Where can templates be stored within Dynamics 365? 

Templates can be stored in:

  • Dynamics 365's document library

  • SharePoint integration

  • EDocGen's template repository


  1. How do you enable the Developer tab in Word for template creation? 

To enable the Developer tab:

  1. Open Word Options.

  2. Select Customize Ribbon.

  3. Under Main Tabs, check the box for Developer.

  4. Click OK to save changes.


  1. What are the template size limitations? 

EDocGen supports templates up to 100MB, but for best performance, optimize templates larger than 10MB by:

  • Breaking large templates into smaller, reusable components.

  • Compressing or optimizing embedded images and media.

  • Using external references for frequently reused content.

  • Ensuring data queries are efficient to avoid delays during processing.


  1. How can authentication issues be resolved? 

To resolve authentication problems:

  • Check Azure AD configurations and permissions.

  • Verify client credentials to confirm the accuracy of client secrets and keys.

  • Validate token processes to ensure tokens are generated, refreshed, and managed correctly.

  • Review system logs to look for specific error messages and identify root causes.

Proactively engage in regular monitoring and audits to minimize recurring authentication issues.

  1. What output formats are supported for generated documents?

EDocGen supports a wide range of output formats:

  • Standard formats: PDF, DOCX, PPTX, Excel

  • Web formats: HTML and responsive layouts for online use

  • Print formats: PCL5 and PostScript for professional printing

  • Specialized formats: Tailored to meet specific industry needs

Popular Posts

.