You are here:
Salesforce Document Generation Sample Apex Codes
These Apex code samples demonstrate how to automate and manage document generation in Salesforce. They cover key tasks like server-side and batch document generation, as well as handling blocked requests by retrying them. Tools like the DocGenRetryBlockedBatch class help developers and admins customize and streamline document-related processes.
Required Editions
| Available in: Lightning Experience |
| Available in: Professional, Enterprise, Unlimited, and Developer Editions |
- Sample Apex Code for Server-Side Document Generation
Here's a sample code that demonstrates how to generate documents on the server by inserting a DocumentGenerationProcess record. You can generate a document on the server either by directly passing token data, or by sending document template details and letting Salesforce fetch token data automatically. - Sample Apex Code for Generating Quotes in Batch
Here is a sample of Apex code that carries out two main functions. First, it creates a record named DocGenerateBatchProcess which is responsible for generating quotes. Second, it creates a list of 100 quote documents and links these documents with the DocGenerateBatchProcess record. To start a batch using Apex, update the Status field to InProgress. This value is case sensitive, and the batch runs automatically after the status is updated. - Retrieve Blocked Server-Side Document Generation Requests Using Apex Class
Retrieve blocked server-side document generation requests for specific timeframes. Blocked requests are reprocessed via new server-side document generation requests.
Sample Apex Code for Server-Side Document Generation
Here's a sample code that demonstrates how to generate documents on the server by inserting a DocumentGenerationProcess record. You can generate a document on the server either by directly passing token data, or by sending document template details and letting Salesforce fetch token data automatically.
Directly Pass Token Data
Use this approach to when you want to define and control the token values that Salesforce uses during the document generation request. See DocumentGenerationProcess
DocumentGenerationProcess documentGeneration = new DocumentGenerationProcess();
documentGeneration.Type = 'GenerateAndConvert';
documentGeneration.RequestText = JSON.serialize(new Map<String, Object>{
'keepIntermediate' => true,
'title' => 'Quote Details',
'templateContentVersionId' => '068Ws00000BXC2aIAH'
});
documentGeneration.ReferenceObject = '001Ws00003FrP4dIAF';
documentGeneration.TokenData = JSON.serialize(new Map<String, String>{
‘Name => ’John P’,
});
documentGeneration.DocGenApiVersionType = 'Advanced';
insert documentGeneration;Send Document Template Details to Fetch Token Data Automatically
Use this approach to automatically resolve token data based on the document template’s configuration. When you use DocumentInputType = DocumentTemplate, Salesforce automatically resolves token data based on the template’s configured data mappings, such as DataRaptor Extracts.
DocumentGenerationProcess documentGeneration = new DocumentGenerationProcess();
documentGeneration.Type = 'GenerateAndConvert';
documentGeneration.RequestText = JSON.serialize(new Map<String, Object>{
'keepIntermediate' => true,
'title' => 'Quote Details',
'templateContentVersionId' => '068Ws00000BXC2aIAH'
});
documentGeneration.ReferenceObject = '001Ws00003FrP4dIAF';
documentGeneration.DocumentInputType = 'DocumentTemplate';
documentGeneration.DataRaptorInput = '{"Id":"0017Y00001jt9cVQAQ"}'; // Pass ID Which should be the Input ID to the Extract DataMapper
documentGeneration.DocGenApiVersionType = 'Advanced';
documentGeneration.DocumentTemplateId = '2dtWs000000KELNIA4';
insert documentGeneration;
Send Token Data Using a JSON File
Use this approach when your token data is stored in a JSON file. Upload the JSON file to Salesforce Files, and then set the TokenDataContentDocumentId field on the DocumentGenerationProcess record to the uploaded JSON file’s ContentDocumentId. During server-side document generation, Salesforce reads the JSON from the file and uses it as token data.
DocumentGenerationProcess documentGeneration = new DocumentGenerationProcess();
documentGeneration.Type = 'GenerateAndConvert';
documentGeneration.RequestText = JSON.serialize(new Map<String, Object>{
'keepIntermediate' => true,
'title' => 'Quote Details',
'templateContentVersionId' => '068Ws00000BXC2aIAH'
});
documentGeneration.ReferenceObject = '001Ws00003FrP4dIAF';
// Uploaded JSON File ContentDocument ID
documentGeneration.TokenDataContentDocumentId = '069WU00000ImN3BYAV';
documentGeneration.DocGenApiVersionType = 'Advanced';
insert documentGeneration;Sample Apex Code for Generating Quotes in Batch
Here is a sample of Apex code that carries out two main functions. First, it creates a record named DocGenerateBatchProcess which is responsible for generating quotes. Second, it creates a list of 100 quote documents and links these documents with the DocGenerateBatchProcess record. To start a batch using Apex, update the Status field to InProgress. This value is case sensitive, and the batch runs automatically after the status is updated.
Create a DocGenerateBatchProcess record for generating quotes
DocGenerationBatchProcess dgbp = new DocGenerationBatchProcess( Description = 'Generate Quotes in Bulk', Category = 'Quotes');
insert dgbp;
Create a list of 100 quote documents and associate them with the DocGenerateBatchProcess record
DocGenerationBatchProcess dgbp = new DocGenerationBatchProcess( Description = 'Generate Quotes', Category = 'Quotes');
insert dgbp;
List<DocumentGenerationProcess> dgpList = new List<DocumentGenerationProcess>();
String quoteId = '0Q0OG0000000Yoc0AE';
String quoteTemplateContentVersionId = '068OG0000003iy6YAA';
String sampleTokenData = '{"SUBSCRIBER_NAME":"Subname","STREET1":"Panathur","CITY":"Blr","STATE":"KA","POSTALCODE":"494001","COUNTRY":"India"}';
for(Integer i=1; i<=1; i++) {
String docTitle = 'Quotes' + i;
DocumentGenerationProcess dgp = new DocumentGenerationProcess (
Type = 'GenerateAndConvert', Status = 'InProgress',
RequestText='{"keepIntermediate":true, "title":"' + docTitle + '","templateContentVersionId":"'+quoteTemplateContentVersionId+'"}',
TokenData = sampleTokenData,
ReferenceObject = quoteId,
DocGenApiVersionType='Advanced',
DocGenerationBatchProcessId = dgbp.Id
);
dgpList.add(dgp);
}
insert dgpList;
Parameters
| Parameter | Description |
|---|---|
| DocGenApiVersionType | Defines the API version that you want to use for document generation. To support rich text and hyperlink tokens for document generation process records, set the Doc Generation API Version Type setting to Advanced. |
| docTitle | Document title. |
| quoteId | ID of the quote. |
| quoteTemplateContentVersionId | Document template content version ID. |
| ReferenceObject | Indicates the object that the generated document is attached to. In the sample Apex code, Account ID is the reference object. The generated document is saved in the Notes and Attachments section of the account. |
| requestText |
|
| Status | Status of the document generation batch process request: Canceled, Completed, In Progress, New, or Paused. |
| templateContentVersionId | ID of the document associated with the batch process. |
| TokenData | Stores the JSON key-value pair that's used as an input for server-side document. |
| Type | GenerateAndConvert: Generates a Word document and creates a PDF document. |
Retrieve Blocked Server-Side Document Generation Requests Using Apex Class
Retrieve blocked server-side document generation requests for specific timeframes. Blocked requests are reprocessed via new server-side document generation requests.
- Sample Code to Retrieve Blocked Requests
Modify the sample code to create an Apex class for retrieving blocked server-side document generation requests. - Create DocGenRetryBlockedBatch Apex Class
After creating the code for retrieving blocked requests, create an Apex class in the Developer Console. - Retrieve and Reprocess Blocked Requests
After creating an Apex class, run the code for retrieving blocked requests in the Developer Console. Ensure that the start time and end time are defined in the Sample Code to Retrieve Blocked Requests.
Sample Code to Retrieve Blocked Requests
Modify the sample code to create an Apex class for retrieving blocked server-side document generation requests.
The required input parameters for the code include:
| Parameter | Description |
|---|---|
| startTime | Start time of the timeframe to retrieve blocked requests. |
| endTime | End time of the timeframe to retrieve blocked requests. |
Sample Code
Global class DocGenRetryBlockedBatch implements Database.Batchable<sObject> {
private DateTime startTime;
private DateTime endTime;
public DocGenRetryBlockedBatch(DateTime startTime, DateTime endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
DateTime dt = System.Now().addHours(-1);
String query = 'SELECT Id, Type ,RequestText, TokenDataContentDocumentId , TokenData from DocumentGenerationProcess where Status =\'Blocked\' and LastModifiedDate >=:startTime and LastModifiedDate <=:endTime';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<DocumentGenerationProcess> blockedList) {
List<DocumentGenerationProcess> ls = new List<DocumentGenerationProcess>();
for(DocumentGenerationProcess blockedObject:blockedList)
{
DocumentGenerationProcess myCustomObject = new DocumentGenerationProcess (
Type = blockedObject.Type, Status = 'InProgress',
RequestText= blockedObject.RequestText,
TokenDataContentDocumentId= blockedObject.TokenDataContentDocumentId,
TokenData = blockedObject.TokenData
);
ls.add(myCustomObject);
}
insert ls;
}
global void finish(Database.BatchableContext BC) {
// execute any post-processing operations
}
}
Create DocGenRetryBlockedBatch Apex Class
After creating the code for retrieving blocked requests, create an Apex class in the Developer Console.
-
Click the quick access menu
and select Developer Console.
- Select File | NewApex Class.
- For Name, enter the name as DocGenRetryBlockedBatch, and then click OK.
-
Enter the code that you created for retrieving blocked requests into the
dialog.
For more information, see Sample Code to Retrieve Blocked Requests.
- Save your changes.
Retrieve and Reprocess Blocked Requests
After creating an Apex class, run the code for retrieving blocked requests in the Developer Console. Ensure that the start time and end time are defined in the Sample Code to Retrieve Blocked Requests.
-
Click the quick access menu
and select Developer Console.
- From the Debug menu, select Open Execute Anonymous Window.
-
In the Enter Apex Code dialog, enter this sample statement:
DocGenRetryBlockedBatch dgrb = new DocGenRetryBlockedBatch( DateTime.newInstance(2022,10,17), DateTime.now()); Database.executeBatch(dgrb); - Select the statement you pasted.
- Click Execute Highlighted.
- Close the Developer Console.

