Generate PDF documents from Salesforce
Posted by admin
Creating Documents is universal truth across organizations. Every organization either big or small.
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!
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.
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: |
↓
Set API Permissions: |
↓
Generate Client Credentials: Obtain and securely store access tokens. |
Once OAuth is configured, you're ready to design and manage templates.
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) |
|
Contracts, proposals, text-heavy documents |
|
|
Finalized documents, secured forms |
PowerPoint (PPTX) |
|
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.
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 |
Navigate to EDocGen Settings
Access the EDocGen integration settings in your Dynamics 365 application.
Select Azure AD Authentication
Choose the Azure Active Directory (AD) authentication method for secure access.
Provide Credentials
Enter the required admin credentials and grant necessary permissions for the application.
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.
Authentication Steps:
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.
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.
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}`);
}
}
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 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
Apply Filters
Navigate Related Data
|
Step 2: Mapping Dynamics 365 Data to Templates |
Define Field Relationships
Handle Data Conversions
Process Related Records
Account for Empty Fields
|
EDocGen extends beyond basic document generation, offering advanced capabilities to streamline workflows and enhance efficiency.
Here’s an overview of its top features:
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.
Prepare digital documents for professional printing with ease. With EDocGen, you can:
Convert generated files into formats like PCL5 or PostScript.
Customize paper sizes and printing specifications.
Manage bulk print jobs efficiently.
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.
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. |
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.
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:
Assess your current document generation needs.
Review your Dynamics 365 environment requirements.
Plan a comprehensive template strategy.
Start with a pilot project to demonstrate ROI.
Scale the solution across your organization.
EDocGen supports Microsoft Word templates created in Word 2013 and newer versions, with the best compatibility in Microsoft 365.
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.
Templates can be stored in:
Dynamics 365's document library
SharePoint integration
EDocGen's template repository
To enable the Developer tab:
Open Word Options.
Select Customize Ribbon.
Under Main Tabs, check the box for Developer.
Click OK to save changes.
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.
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.
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
Posted by admin
Creating Documents is universal truth across organizations. Every organization either big or small.
Posted by admin
Integrate with the Azure SQL Server to generate PDF documents from existing templates.
Posted by admin
Generate PDF documents from existing templates and send them by email from .Net application.