Salesforce Document Automation Explained (Flow, Apex & API) (2026)
Salesforce document automation is the process of generating documents from Salesforce records automatically — triggered by an event such as a record update, a stage change, a button click, or an API call — instead of a user manually creating each document by hand.
The manual approach does not scale. As soon as a team is producing contracts, quotes, invoices, or letters in any volume, generating each one by hand becomes slow, error-prone, and impossible to keep consistent. Salesforce document automation removes the manual step entirely: the document is produced the moment the trigger event fires, populated with the right data, and delivered wherever it needs to go.
This guide explains how document automation works in Salesforce using the three tools that drive it — Flow, Apex, and the API — when to reach for each, and how to build an automation that stays within governor limits at scale. For the foundation, see our guide on Salesforce document generation.
What is Salesforce document automation?
Salesforce document automation is the generation of documents from record data without a manual step, driven by an automation tool that populates a template and produces the finished document when a defined event occurs. Where manual document generation requires a user to open a record, choose a template, and click generate, automated generation happens on its own the moment its trigger fires.
Every automation has the same three parts: a trigger that decides when a document should be created, a template that defines what the document looks like, and an output action that decides what happens to the document once it exists — attach it to the record, email it, or send it for signature.
The three tools that connect these parts are Flow, Apex, and the Salesforce API. Flow handles declarative, clicks-not-code automation. Apex handles complex logic and high-volume processing. The API lets external systems trigger generation from outside Salesforce. Most real-world automations use one of these, and larger orgs often combine them.
The payoff is consistency and speed: every document is generated the same way from the same data, with no re-keying, no missed fields, and no waiting for someone to remember to produce it.
What can trigger automatic document generation?
Automatic document generation can be triggered by almost any event in Salesforce — a record change, a stage transition, a field condition, a button click, a scheduled job, or an external API call. The right trigger is simply the point in your process where the document needs to appear.
Record created or updated
Generate a document when a record is created or a key field changes — for example, produce a welcome letter the moment a new Account is created.
Stage or status change
Generate a contract when an Opportunity moves to Closed Won, or an invoice when an order status changes to Fulfilled.
Field condition met
Generate only when a condition is true — a deal above a threshold, an Account in a specific industry, or a checkbox being set.
Button or quick action
Let a user trigger generation on demand with a single click from the record page, when full automation is not appropriate.
Scheduled job
Generate documents in bulk on a schedule — monthly statements, weekly summaries, or renewal notices produced overnight.
External API call
Let an external portal, billing system, or partner application trigger generation from outside Salesforce through the API.
Read more: How to Add Conditional Logic to Salesforce Documents (IF/THEN) (2026)
Automating documents with Flow
Flow is the declarative, no-code way to automate document generation in Salesforce, and it is the right starting point for most automations. A record-triggered flow fires when a record meets a condition, and an invocable action generates the document — all configured with clicks rather than code.
The pattern is consistent: a record-triggered flow listens for the event, evaluates the entry conditions, and calls an invocable document-generation action, passing the record ID and the template to use. The generated document is then handled by the flow’s next element.
TRIGGER: Opportunity is updated
CONDITION: StageName is changed to "Closed Won"
ACTION: Generate Document
• recordId = {!$Record.Id}
• template = "Sales Agreement"
• output = attach to record + send for signature
Flow is ideal when the logic is straightforward and an admin — not a developer — will own the automation long term. It is easy to read, easy to change, and easy to hand over.
A record-triggered flow fires on stage change and calls an invocable action to generate the document — no code required.
Automating documents with Apex
Apex is the code-based option for document automation, and it is the right choice when the logic is complex, the volume is high, or you need precise control over how records are processed. Where Flow reaches its limits — heavy branching logic, processing thousands of records, or coordinating callouts — Apex takes over.
A common pattern is to expose the generation logic as an @InvocableMethod so Flow can still orchestrate the process while Apex does the heavy lifting. For bulk jobs, generation is moved into asynchronous Apex — Batch, Queueable, or Scheduled — so large volumes are processed without hitting synchronous limits.
public class DocGenAction {
@InvocableMethod(label='Generate Document')
public static List<Result> run(List<Request> reqs) {
// resolve template + record, generate, return file Id
}
}
global class DocGenBatch implements Database.Batchable<SObject> {
// process records in chunks to respect governor limits
global void execute(Database.BatchableContext bc, List<SObject> scope) {
// generate one document per record in the batch
}
}
The strongest pattern for most orgs is a hybrid: Flow orchestrates the business process and calls an @InvocableMethod, while Apex executes the generation. Admins keep control of the process; developers own the complex logic.
Automating documents with the Salesforce API
The Salesforce API lets an external system trigger document generation from outside the org, which is essential when the event that should produce a document happens somewhere other than Salesforce. A customer portal, a billing platform, or a partner application can call into Salesforce and start generation programmatically.
The usual approach is to expose an Apex REST endpoint with @RestResource, or to invoke a flow through the API. The external system authenticates, sends the record ID and template reference, and Salesforce generates the document and returns a reference to it.
@RestResource(urlMapping='/generate-doc/*')
global class DocGenRest {
@HttpPost
global static String generate(String recordId, String template) {
// generate the document, return the file reference
}
}
Secure every external endpoint. Authenticate the calling system, validate every incoming ID against the caller’s permissions, and never trust a record ID from an external request without checking access. An open generation endpoint is a data-exposure risk.
Read more: How to Generate Documents in Salesforce: Step-by-Step Guide (2026)
Flow, Apex, or API: which should you use?
Choose Flow for declarative automation, Apex for complex or high-volume logic, and the API when the trigger lives in an external system. The three are not competitors — they cover different situations, and many orgs use all three.
| Tool | Best for | Owned by | Watch out for |
|---|---|---|---|
| Flow | Stage changes, record updates, on-demand buttons, simple logic | Admins | Complex branching and true bulk volume |
| Apex | Complex logic, bulk generation, asynchronous jobs, fine control | Developers | Requires code, test coverage, and maintenance |
| API | Triggers originating in external systems | Developers / integrators | Authentication and access validation |
A good rule of thumb: start with Flow. Move to Apex only when Flow can’t express the logic or can’t handle the volume. Add the API only when the trigger genuinely lives outside Salesforce.
Building a document automation: step by step
Building a document automation follows five steps: choose the trigger, select the tool, map the template and data, define the output action, and test in bulk with error handling. Each step is covered below.
Choose the trigger event
Decide exactly what should start generation — a record update, a stage change, a button click, a schedule, or an external API call. Pin down the single moment in your process where the document needs to exist, and make that your trigger.
Select the automation tool
Pick Flow for declarative automation, Apex for complex logic or bulk volume, or the API for external triggers. When in doubt, start with Flow and escalate to Apex only when the logic or scale demands it.
Map the template and data
Point the automation at the document template and the record whose field data will populate it. Confirm every merge field resolves and that any conditional sections are driven by the correct fields before going live.
Define the output action
Specify what happens to the generated document — attach it to the record, email it to a contact, send it for signature, or hand it to the next step in the process. The output action is where automation delivers its value.
Test in bulk and handle errors
Test against many records at once, not just one. Verify governor limits are respected under load, confirm the output is correct for edge-case records, and add error handling so a single failed record doesn’t silently break the batch. See the governor limits section below.
Governor limits and scaling document automation
Document automation runs inside Salesforce transactions, so it is subject to governor limits on CPU time, heap size, and callouts — and well-built automation is designed around them from the start. An automation that works on one record can fail badly when it runs against thousands at once.
Three principles keep automation stable at scale.
Process in batches
Generate documents in chunks using Batch Apex rather than all at once. Batching keeps each transaction within CPU and heap limits no matter how many records are in scope.
Go asynchronous for volume
Move bulk generation into Queueable or Batch Apex so heavy work runs outside the synchronous limits that constrain a single transaction.
Never generate inside a loop
Avoid calling a generation step once per iteration of a loop. Collect the records first, then process them together so you don’t multiply governor consumption.
Handle errors per record
Trap failures at the record level so one bad record doesn’t roll back an entire batch, and log failures so they can be retried or investigated.
Test at realistic volume before go-live. An automation that passes on a handful of records can still hit CPU or heap limits at production scale. Load-test against a batch that reflects your real peak volume, not a convenient sample of two or three records.
Frequently asked questions about Salesforce document automation
Salesforce document automation is what turns document generation from a manual task into an invisible part of your process. Whether the trigger is a stage change handled by Flow, a bulk job driven by Apex, or an external event arriving through the API, the outcome is the same: the right document, generated from the right data, delivered without anyone lifting a finger.
For the foundation that automation is built on, see our guide on how to create Salesforce document templates, or visit Dochly document generation to see automation working inside a fully native Salesforce app.