Document Generation merges record data into a Word template and saves the result, as Word and PDF, to Salesforce Files. Quote proposals, contract documents and invoices all run on it. The Contracts guide explains the parts as an admin sees them. This page is the code side: what a template looks like as metadata, how to deploy one with its Data Mappers, and how to ask for a document from Apex or a Flow.
We built one invocable Apex class, deployed it with its test to our lab org, and used it to generate a real quote proposal there on 2026-11-08. That run is described under Test and debug.
What it's for
Reach for this page when:
- A template or its Data Mappers changed in a sandbox and must reach other orgs the same way every time.
- Documents should come from automation, such as a Flow when a quote is approved, not from a rep clicking a quick action.
- A generated document looks wrong, and you need to tell a template problem from a data problem.
- Invoice PDFs must be produced in bulk or on demand from Billing.
How it works
A template is two files
In short: a .dt file that is the Word document itself, and a .dt-meta.xml that says how to fill it.
The DocumentTemplate metadata type extends MetadataWithContent: the content is the .dt file, and both live in documentTemplates/.1 The .dt is an ordinary DOCX zip. The quote proposal template we retrieved from our lab org, RLM_QuoteProposal_1.dt, is 3.9 MB because it carries its fonts and seven images inside it.
The fields that matter most in the -meta.xml:1
| Field | What it holds |
|---|---|
name, uniqueName, versionNumber |
The template's name, its versioned unique name (RLM_QuoteProposal_1) and the version |
type |
MicrosoftWord, MicrosoftPowerpoint, Microsoft365Word, HTMLArchive or Web |
usageType |
Where the template is used. The reference lists Contract_Lifecycle_Management and Revenue_Lifecycle_Management |
tokenMappingMethodType |
Where the data comes from: OmniDataTransform, ContextService or CustomClass |
extractOmniDataTransformName, mapperOmniDataTransformName |
The Data Mapper pair, for OmniDataTransform |
contextDefinitionName, contextMappingName |
The context definition and mapping, for ContextService |
tokenList |
Every token the template uses, comma-separated, with : for nesting (Line:CQL:ProductName) |
documentGenerationMechanism |
ClientSide (the default) or ServerSide |
isActive, status |
Whether it can generate; status is Active, Draft or Archived |
The reference's usageType list is shorter than what orgs use. Our lab org also has Invoice and Account_Statement templates, which Billing creates.
Template files live in a Salesforce Files library, the Docgen Document Template Library (developer name DocgenDocumentTemplateLibrary). The DocGen setting names it, and each template's Word file is a document in it with the template's name as its title.4 You can have several versions of a template, but only one is active at a time.2
DocumentTemplate record per version, with the Word file kept in the template library.Tokens
In short: double curly braces in the Word file; the prefix says what kind of token it is.
Salesforce's token notation:3
| Token | Notation | What it does |
|---|---|---|
| Variable | {{token_name}} |
Prints one value. It takes the formatting of the first brace |
| Repeating content | {{#token_name}} ... {{/token_name}} |
Repeats the section once per item in a JSON array |
| Empty array | {{^token_name}} ... {{/token_name}} |
Shows the section once when the array is empty or missing |
| Condition | {{#IF_token_name}} ... {{/IF_token_name}} |
Shows the section once when the value is true. {{^IF_...}} inverts it |
| Image | {{IMG_name}} |
Inserts a dynamic image |
| Hyperlink | {{HYP_name}} |
Inserts a dynamic link |
| Rich text | {{RTB_name}} |
Inserts rich text, keeping its formatting |
Two rules catch people. A condition token must get a real Boolean: a string or a number always counts as true. And the data's key must carry the same prefix as the token, so {{^IF_resident}} needs a key named IF_resident.3 Plain variable tokens drop formatting, line breaks included; use rich text for anything multi-line.3
For a table that repeats per line, put the opening tag in the row's first cell and the closing tag in its last. The launchpad's proposal nests three levels: {{#Line}}, then {{#CQL}} for child lines, then {{#CQL2}}.
Where the data comes from
In short: a Data Mapper pair shapes JSON for the tokens, or a Context Service mapping does it without OmniStudio.
With OmniDataTransform, generation runs the Extract named on the template against the record, passes its output to the Transform, and merges the result into the tokens. The Transform's output keys are the token names. You can run the Extract on its own to see exactly what the template will get; OmniStudio from the command line shows the call, against the same quote extract.
With ContextService, the template names a context definition and mapping, and the record's fields reach the tokens through that mapping. The launchpad ships both kinds of quote proposal, RLM_QuoteProposal and RLM_QuoteProposal_CS, filling the same tokens.
The setting
In short: DocumentGenerationSetting turns on server-side and batch generation and names the template library.
The type lives in documentGenerationSettings/. This is our lab org's, retrieved as DocumentGenerationSetting:DocGen on 2026-11-08:
<DocumentGenerationSetting xmlns="http://soap.sforce.com/2006/04/metadata">
<batchDocGnrnPctLimitPerHour>0.6</batchDocGnrnPctLimitPerHour>
<documentTemplateLibraryName>DocgenDocumentTemplateLibrary</documentTemplateLibraryName>
<generationMechanism>ServerSide</generationMechanism>
<isBatchDocGnrnEnabled>true</isBatchDocGnrnEnabled>
<isInProgRqstTmotEnab>false</isInProgRqstTmotEnab>
<isServerSideDocGenEnabled>true</isServerSideDocGenEnabled>
<masterLabel>DocGen</masterLabel>
<previewType>PDF</previewType>
</DocumentGenerationSetting>
documentTemplateLibraryName and masterLabel are required. inProgDocGenRqstTmot sets how many hours (1 to 24, default 6) a request may stay in progress before it's marked failed, when isInProgRqstTmotEnab is on. Setting isServerSideDocGenEnabled isn't enough on its own: server-side generation needs a DocGen license, and Salesforce says access must be requested.4 Billing's invoice PDFs need both server-side and batch generation turned on before Document Generation is switched on in Billing Settings.5
A request is a record
In short: insert a DocumentGenerationProcess, and the platform generates the files and writes back the result.
Every generation, from the quick action, Billing or your code, is a DocumentGenerationProcess record. The fields you set:6
| Field | Value |
|---|---|
Type |
Generate (DOCX only, the default), Convert, GenerateAndConvert (DOCX then PDF) or MergePDF |
DocumentTemplateId |
The template, a 2dt ID |
ReferenceObject |
The record the files attach to |
DocumentInputType |
DocumentTemplate (the default is None) |
DataRaptorInput |
For Data Mapper templates, the Extract's input, such as {"Id":"0Q0..."} |
RequestText |
JSON options, such as the file title and keepIntermediate. A 255-character field |
DocGenAdditionalInputType, DocGenAdditionalInput |
For Context Service templates: ContextService, and the record ID as plain text |
Then you read two fields. Status starts as InProgress and ends as Success or Failure.6 On success, ResponseText holds the generated ContentVersion IDs, comma-separated. In our run the DOCX came first and the PDF second.
DocumentGenerationProcess, then reads Status and ResponseText once the platform has generated the files.Salesforce's object reference marks the two DocGenAdditionalInput fields "for internal use only". The launchpad uses them for its Context Service template, and so does our class, but that's an undocumented contract that could change.6
Billing's entry points
In short: invoices have their own actions; under them is the same request record.
Billing doesn't need your code for invoices:
- Generate Invoice Documents (
/services/data/v68.0/actions/standard/generateInvoiceDocuments) takes aninvoiceBatchRunIdand generates PDFs for the batch's draft and posted invoices asynchronously. It needs BillingDocGenon and an active invoice template.7 - Generate On-Demand Invoice Document (
POST /revenue/billing/document/actions/generate, API 66.0) generates one invoice's document, with optionaldocumentTemplateId,documentTitleandshouldForceRegenerate. Its response includes thedocumentGenerationProcessId, so you watch it the same way.8
Our lab org already had three invoice runs from Billing's default template, all GenerateAndConvert and all Success.
Build it
Deploy a template and its Data Mappers
Deploy in this order, because each step needs the one before:
- Any custom fields the Data Mappers read, such as formula fields on Quote.
- The Data Mapper pair (
OmniDataTransform). - The template (
DocumentTemplate, both files). - Activate the template.
A manifest for the launchpad's quote proposal:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>RLMQuoteExtractBasic_1</members>
<members>RLMQuoteTransformBasic_1</members>
<name>OmniDataTransform</name>
</types>
<types>
<members>RLM_QuoteProposal_1</members>
<name>DocumentTemplate</name>
</types>
<version>66.0</version>
</Package>
sf project retrieve start --manifest manifest/package.xml --target-org <source>
sf project deploy start --manifest manifest/package.xml --target-org <target>
We ran the retrieve against our lab org on 2026-11-08; it returned both Data Mappers and both template files. We didn't redeploy a template there, so the next part is the launchpad's experience, not ours. Its build notes say a template always deploys inactive, and each deploy adds a new version. After deploying, it runs anonymous Apex that finds the highest version of each template and activates it:
Map<String, DocumentTemplate> latestByName = new Map<String, DocumentTemplate>();
for (DocumentTemplate t : [SELECT Id, Name, VersionNumber, IsActive FROM DocumentTemplate
WHERE Name LIKE 'RLM_%' ORDER BY Name, VersionNumber]) {
latestByName.put(t.Name, t); // last one wins: the highest version
}
List<DocumentTemplate> toActivate = new List<DocumentTemplate>();
for (DocumentTemplate t : latestByName.values()) {
if (!t.IsActive) { t.IsActive = true; toActivate.add(t); }
}
update toActivate;
Change RLM_% to your own prefix. The launchpad also fixes each template's Word file after the deploy (Watch out).
Request a document from Apex or Flow
We modelled this on the launchpad's RLM_DocumentGenerationCreate. It takes a record and a template, checks the template is active, and inserts one DocumentGenerationProcess per request, filled the way the template's mapping method needs. It returns the process IDs; generation happens after the transaction commits.
/**
* Asks Document Generation for a document: one DocumentGenerationProcess per request.
* Generation runs asynchronously; read Status and ResponseText on the returned record.
*/
public with sharing class QBDocumentRequest {
@TestVisible static final Integer TITLE_MAX = 200; // RequestText is a 255-character field
public class Request {
@InvocableVariable(label='Record Id' description='The quote (or other record) the document is for' required=true)
public Id recordId;
@InvocableVariable(label='Document Template Id' description='An active DocumentTemplate (2dt)' required=true)
public Id templateId;
@InvocableVariable(label='Title' description='Title of the generated file')
public String title;
}
public class Response {
@InvocableVariable(label='Document Generation Process Id')
public Id processId;
}
@InvocableMethod(label='Request Document Generation' category='Document Generation'
description='Creates a DocumentGenerationProcess that generates a DOCX from a template and converts it to PDF.')
public static List<Response> requestDocuments(List<Request> requests) {
Set<Id> templateIds = new Set<Id>();
for (Request r : requests) {
if (r == null || r.recordId == null || r.templateId == null) {
throw new IllegalArgumentException('QBDocumentRequest: recordId and templateId are required.');
}
templateIds.add(r.templateId);
}
Map<Id, DocumentTemplate> templates = new Map<Id, DocumentTemplate>([
SELECT Id, TokenMappingMethodType, IsActive FROM DocumentTemplate WHERE Id IN :templateIds
]);
List<DocumentGenerationProcess> processes = new List<DocumentGenerationProcess>();
for (Request r : requests) {
DocumentTemplate t = templates.get(r.templateId);
if (t == null) throw new IllegalArgumentException('QBDocumentRequest: no DocumentTemplate ' + r.templateId);
if (!t.IsActive) throw new IllegalArgumentException('QBDocumentRequest: template ' + r.templateId + ' is not active');
processes.add(processFor(r, t.TokenMappingMethodType));
}
insert processes;
List<Response> responses = new List<Response>();
for (DocumentGenerationProcess p : processes) {
Response res = new Response();
res.processId = p.Id;
responses.add(res);
}
return responses;
}
/** The record DocGen picks up. Plain Apex, so a test can check every field. */
@TestVisible static DocumentGenerationProcess processFor(Request r, String mappingMethod) {
DocumentGenerationProcess p = new DocumentGenerationProcess(
Type = 'GenerateAndConvert', // DOCX, then PDF
ReferenceObject = r.recordId, // the record the files attach to
DocumentTemplateId = r.templateId,
DocumentInputType = 'DocumentTemplate',
DocGenApiVersionType = 'Advanced',
RequestText = JSON.serialize(new Map<String, Object>{
'keepIntermediate' => true, // keep the DOCX as well as the PDF
'title' => String.isBlank(r.title) ? 'Document' : r.title.left(TITLE_MAX)
})
);
if (mappingMethod == 'ContextService') {
// Context Service templates take the root record Id as a plain string.
p.DocGenAdditionalInputType = 'ContextService';
p.DocGenAdditionalInput = String.valueOf(r.recordId);
} else {
// Data Mapper templates take the Extract's input JSON.
p.DataRaptorInput = JSON.serialize(new Map<String, Object>{ 'Id' => r.recordId });
}
return p;
}
}
DocGenApiVersionType = 'Advanced' is copied from the launchpad; the object reference doesn't describe that field, so we kept the launchpad's value rather than guess.
In a Flow, add it as an Action: the label and category on @InvocableMethod (Request Document Generation, under Document Generation) are what Flow Builder lists. We called it through REST for this page and didn't open Flow Builder. Look the template up by name and IsActive, not by a pasted ID (Watch out). The launchpad's quote flow then waits on the DocGenProcStsChgEvent platform event in a small Lightning web component, with polling as a fallback. A record-triggered flow can instead react when the process record's Status changes; we haven't built either for this page.
Read the result
sf data query --target-org <alias> --query "SELECT Status, ResponseText FROM DocumentGenerationProcess WHERE Id = '<process id>'"
sf data query --target-org <alias> --query "SELECT Id, Title, FileExtension, ContentSize FROM ContentVersion WHERE Id IN ('<first id>', '<second id>')"
Test and debug
The unit test
Generation is asynchronous and doesn't run inside a test, so we assert on what our code inserted, and on the checks that stop a bad request. The test creates its own templates, so it doesn't depend on the org's.
@IsTest
private class QBDocumentRequestTest {
// Generation itself is asynchronous and doesn't run in a test; we assert on what we inserted.
@TestSetup static void templates() {
insert new List<DocumentTemplate>{
new DocumentTemplate(Name = 'QBTestOdt', Type = 'MicrosoftWord', TokenMappingType = 'JSON',
TokenMappingMethodType = 'OmniDataTransform', IsActive = true),
new DocumentTemplate(Name = 'QBTestCs', Type = 'MicrosoftWord', TokenMappingType = 'JSON',
TokenMappingMethodType = 'ContextService', IsActive = true,
ContextDefinitionName = 'RLM_QuoteDocGenContext', ContextMappingName = 'QuoteDocGenMapping'),
new DocumentTemplate(Name = 'QBTestDraft', Type = 'MicrosoftWord', TokenMappingType = 'JSON',
TokenMappingMethodType = 'OmniDataTransform', IsActive = false)
};
}
static Id template(String name) {
return [SELECT Id FROM DocumentTemplate WHERE Name = :name LIMIT 1].Id;
}
static Id quoteId() {
Account a = new Account(Name = 'QB DocGen Test');
insert a;
Opportunity o = new Opportunity(Name = 'QB DocGen Test', AccountId = a.Id, StageName = 'Prospecting',
CloseDate = Date.today().addDays(30));
insert o;
Quote q = new Quote(Name = 'QB DocGen Test', OpportunityId = o.Id, Pricebook2Id = Test.getStandardPricebookId());
insert q;
return q.Id;
}
static QBDocumentRequest.Request request(Id recordId, Id templateId, String title) {
QBDocumentRequest.Request r = new QBDocumentRequest.Request();
r.recordId = recordId;
r.templateId = templateId;
r.title = title;
return r;
}
@IsTest static void dataMapperTemplateGetsDataRaptorInput() {
Id q = quoteId();
Test.startTest();
List<QBDocumentRequest.Response> res = QBDocumentRequest.requestDocuments(
new List<QBDocumentRequest.Request>{ request(q, template('QBTestOdt'), 'Proposal Q-1') });
Test.stopTest();
DocumentGenerationProcess p = [
SELECT Type, ReferenceObject, DocumentTemplateId, DocumentInputType, RequestText,
DataRaptorInput, DocGenAdditionalInputType, Status
FROM DocumentGenerationProcess WHERE Id = :res[0].processId
];
Assert.areEqual('GenerateAndConvert', p.Type);
Assert.areEqual(String.valueOf(q), p.ReferenceObject);
Assert.areEqual(template('QBTestOdt'), p.DocumentTemplateId);
Assert.areEqual('DocumentTemplate', p.DocumentInputType);
Assert.areEqual(String.valueOf(q), ((Map<String, Object>) JSON.deserializeUntyped(p.DataRaptorInput)).get('Id'));
Assert.isNull(p.DocGenAdditionalInputType);
Map<String, Object> requestText = (Map<String, Object>) JSON.deserializeUntyped(p.RequestText);
Assert.areEqual('Proposal Q-1', requestText.get('title'));
Assert.areEqual(true, requestText.get('keepIntermediate'));
Assert.areEqual('InProgress', p.Status); // the platform default; generation hasn't run
}
@IsTest static void contextServiceTemplateGetsTheRecordId() {
Id q = quoteId();
DocumentGenerationProcess p = QBDocumentRequest.processFor(request(q, template('QBTestCs'), null), 'ContextService');
Assert.areEqual('ContextService', p.DocGenAdditionalInputType);
Assert.areEqual(String.valueOf(q), p.DocGenAdditionalInput);
Assert.isNull(p.DataRaptorInput);
Assert.areEqual('Document', ((Map<String, Object>) JSON.deserializeUntyped(p.RequestText)).get('title'));
}
@IsTest static void longTitlesStayInsideRequestText() {
DocumentGenerationProcess p = QBDocumentRequest.processFor(
request(quoteId(), template('QBTestOdt'), 'x'.repeat(400)), 'OmniDataTransform');
Assert.isTrue(p.RequestText.length() <= 255, 'RequestText is ' + p.RequestText.length() + ' characters');
}
@IsTest static void refusesInactiveTemplatesAndMissingInput() {
Id q = quoteId();
for (QBDocumentRequest.Request bad : new List<QBDocumentRequest.Request>{
request(q, template('QBTestDraft'), 'Draft'), request(null, template('QBTestOdt'), 'No record') }) {
try {
QBDocumentRequest.requestDocuments(new List<QBDocumentRequest.Request>{ bad });
Assert.fail('Expected IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().startsWith('QBDocumentRequest: '), e.getMessage());
}
}
Assert.areEqual(0, [SELECT COUNT() FROM DocumentGenerationProcess]);
}
}
The first deploy failed all four tests: a Context Service template can't be inserted without ContextDefinitionName ("Enter the context definition name because the token mapping method type is context service"). With that added, on 2026-11-08 we deployed both classes to our lab org (API 66.0), running only this test class. All four tests passed, and all 37 lines of QBDocumentRequest were covered.
The real run
Then we called the deployed method through the REST actions endpoint, which runs the same invocable method a Flow's Action element calls, for the Kingsbridge lab quote (seven lines) and the active RLM_QuoteProposal template. The record and template IDs are our org's; in yours, use your own quote's ID and look the template's ID up by name. rlm-base__my-lab is the alias of the lab org from the setup page.
sf api request rest "/services/data/v66.0/actions/custom/apex/QBDocumentRequest" --method POST \
--body '{"inputs":[{"recordId":"0Q0E2000005u81dKAA","templateId":"2dtE20000003oWYIAY","title":"Kingsbridge proposal (field guide test)"}]}' \
--target-org rlm-base__my-lab
It returned one process ID. Six seconds after it was created, the record read Status = Success and ResponseText = 068E200000LnMoE,068E200000LnOhp: a 3.9 MB DOCX and an 85 KB PDF, both titled from our request and both linked to the quote. In the DOCX, the quote number, the Complete Solution and its six child lines, their quantities and prices, and the $76,000.00 total were filled in, with no {{ left anywhere. Two things weren't right, and neither came from our code: the expiry date was blank, because the quote has none, and an old <# <TableRow Select="/blng__Invoice__c//... tag from another template tool still sits in the launchpad's Word file and prints as text.
Two more things this run showed. Our request had no templateContentVersionId in RequestText, which the launchpad's notes say is required, and it still succeeded. And both quote Data Mappers show active = false in the org, yet generation used them.
When a document comes out wrong
Status = Failure. ReadResponseTextfor the reason.- Blank tokens. Run the Extract on its own (see OmniStudio from the command line). If the key is missing there, it's the mapping; if it's present, check the token's spelling and nesting in the template.
- Inspect the DOCX, not the PDF. With
keepIntermediateon you get the DOCX too. Unzip it and readword/document.xml. Word often splits a token across several runs of text, which is harmless, but it hides tokens from a plain search of the file. - The wrong layout altogether. Compare the template's file in the library with the
.dtin source (the batch deploy issue below).
Watch out
A deployed template comes in inactive, as a new version, even when the file says <isActive>true</isActive>. That's the launchpad's finding, and its files do say true. Activate the version you deployed afterwards, and expect old versions to pile up.
Deploying several templates in one Metadata API request can give all of them the same Word file: the launchpad found every template got the first one's content, alphabetically, with no error. Deploy templates one at a time, or replace each template's file in the library after the deploy, as the launchpad does by uploading the right .dt as a new ContentVersion.
On a fresh org, a Data Mapper that reads custom formula fields can fail on its first insert (the launchpad saw error -692085439), while an update of an existing one works. The launchpad deploys the fields first, then minimal stub Data Mappers, then the real ones, so the real deploy is an update.
Template IDs (2dt...) differ in every org. A Flow with a pasted ID breaks in the next org, and the template to use changes with every new version. Look templates up by name and IsActive. The launchpad's on-demand invoice flow still declares a 2dt constant from the org it was built in, though it now looks the template up by name.
A logo in a template is part of the .dt file: the image bytes sit inside the DOCX. Changing it means editing the Word file and redeploying, not changing a setting. Billing's own invoice logo works differently, through an image token and a Company_Logo file.9
Leave Billing's own Data Mappers, such as BillingDocumentGenerationGetInvoiceDetails, out of source control. In our lab org, Billing's Default Invoice Template runs on it, so deploying your copy changes what Billing's template does. To customize, clone the template and its Data Mappers under your own names, as Billing's setup guide suggests.5
RequestText is a 255-character field, and the title goes inside its JSON. Cap the title, as our class does, rather than find out what a longer one does.
Salesforce marks the Context Service input fields on DocumentGenerationProcess as internal use only. Code that sets them, ours included, depends on behavior Salesforce doesn't document.
Sources
Every numbered note links to the Salesforce page it comes from. We read the Help articles in Chrome and the developer pages as Markdown, on 2026-11-08; the billing developer pages are Salesforce's Winter '27 (264) copies in the launchpad.
- Salesforce Contracts developer guide:
DocumentTemplate(metadata) andDocumentGenerationProcess(object); Metadata API Developer Guide:DocumentGenerationSetting; Salesforce Field Reference:DocumentGenerationProcess, read 2026-11-08 - Salesforce Help: Tokens in Microsoft Word or Microsoft PowerPoint Documents; Omnistudio Document Generation Document Templates; Turn On Invoice PDF Document Generation and Account Statement; Generate Invoice PDFs with Your Company Logo, read 2026-11-08
- Revenue Management developer guide (264 copy): Generate Invoice Documents Action; Generate On-Demand Invoice Document, read 2026-11-08
- Salesforce's rlm-base-dev launchpad, commit c77e638 (2026-10-08):
docs/guides/docgen-setup.md,tasks/rlm_docgen.py,.cursor/skills/document-generation/SKILL.md,cumulusci.yml,RLM_DocumentGenerationCreateand its test, the activation script and theDocGenflows, read 2026-11-08 - Our lab org: the template, Data Mapper and setting retrieves, the class deploy and test run, and the generated quote proposal above, 2026-11-08
The batch-deploy file issue, the formula-field insert failure and "templates always deploy inactive" are the launchpad's findings. We didn't reproduce them in this pass.