Salesforce Documents
Trigger Document Generation From Salesforce Flow: A Clean API Pattern
- Salesforce Flow
- automation API
- Apex
- no-code
- DocForge
The wrong shape: per-template Apex classes
It is common to see a separate Apex class per template: GenerateProposalPDF, GenerateInvoicePDF, GenerateNDA. Each one duplicates logic and drifts. Admins cannot wire any of them into a Flow without dev help.
The right shape is one stable, well-documented Flow-callable action plus an Apex API that takes template ID and source record ID as inputs. Everything else is configuration.
The action interface that Flow loves
- Input:
templateId,sourceRecordId,optionsmap (locale, currency override, attach mode). - Output:
documentId,contentVersionId,fileUrl,status,errorMessage. - Bulk-friendly: accepts a list and returns a list, so screen-flow and record-triggered flows both work.
- Idempotent: same template + record + run key returns the same document; safe to retry.
Patterns Flow admins use
- Quick action on Opportunity: screen flow with template picker → invoke action → show success.
- Record-triggered: when stage = "Closed Won," generate the welcome packet.
- Scheduled flow: monthly statement generation for active accounts.
- Sub-flow in larger automation: contract → e-sign → onboarding email all chained.
Where Apex API stays in the picture
- Apex triggers and asynchronous jobs needing precise control.
- Integration code in managed packages.
- Complex batch jobs that need governor-limit-aware patterns.
- External-system callbacks (webhook receivers) that fan back into Salesforce.
Authentication, permissions, and named credentials
The action must run under the user's permissions (CRUD/FLS on source records) and respect sharing rules. Named credentials handle the external generator endpoint—no hardcoded secrets. Permission sets gate who can invoke the action; specific templates can have stricter permission scoping.
Error handling that admins can debug
- Structured error codes (
TEMPLATE_NOT_FOUND,FIELD_MAPPING_INVALID,SOURCE_RECORD_MISSING_FIELD) with human messages. - Optional fault path in Flow with the error message to display to the user.
- Generator audit log written to a custom object regardless of success/fail.
- Retry semantics documented: which errors are transient (retry) vs permanent (escalate).
Testing the Flow path
- Unit tests for the invocable action with mocked generator endpoint.
- Flow tests with sample data sets covering success and failure paths.
- Sandbox integration test against the real generator.
- Performance test with bulk inputs (200 records in one invocation).
The reusability benefit, with numbers
Before: 12 templates × 8 hours of dev per template change = 96 dev hours per quarter spent on layout tweaks. After: one stable API + admins editing visual templates → dev hours drop to near zero for layout changes; dev focuses on real business logic.
Calling document generation from Flow without governor-limit roulette
Flow excels at orchestration; PDF engines excel at render. Keep heavy work in an invocable action or external API that returns a file ID—not inline Apex string building in a loop over 200 line items.
Design inputs as a structured JSON payload built from Flow formulas so the same action works from record-triggered Flow, screen Flow, and REST.
Invocable action contract
| Input | Type | Required |
|---|---|---|
recordId | Id | Yes |
templateApiName | String | Yes |
locale | String | No (org default) |
attachToRecord | Boolean | Yes |
idempotencyKey | String | Recommended |
Output handling in Flow
- Branch on
successboolean—never assume attach worked because no fault. - Store
contentDocumentIdandfileHashin variables for downstream steps. - On failure, route to fault path with
errorCodefor rep-facing message. - Async path for batches over 50 lines—call @future or queueable from invocable.
- Log each invocation to custom object Document_Generation_Log__c for support.
Example: screen Flow for ad-hoc NDA
Rep launches screen Flow on Opportunity, picks NDA template and signatory contact. Invocable generates PDF in 4 seconds, returns contentDocumentId; Flow shows success toast with link. Same action is reused in record-triggered Flow when Stage = Negotiation—one API surface, two entry points, identical audit log schema.
Bulk and scheduled generation patterns
Record-triggered Flows work for one Opportunity; scheduled Flows batch-closing invoices need queueable handoff when row count exceeds 50. Pass batch ID through idempotency key so partial failures resume without duplicate files.
Surface batch status on a custom dashboard: total, success, failed, retry—finance should not open Debug Log to learn a nightly job stalled.
Version your invocable action API when adding required inputs—Flows fail at runtime without compile-time errors if a new required field deploys before Flow updates.
Expose generation status on the Opportunity layout as a read-only component—reps stop pinging admins when they see In Progress vs Failed with error code.
Document maximum line-item count per invocation in admin guide—Flow timeouts on 400-line Opportunities need batch mode, not repeated clicks.
Pin invocable action versions in Flow metadata so sandbox refreshes do not silently point at deprecated API signatures.
Document automation earns trust when ops owns the pipeline: weekly batch reviews, mapping change control, and a single owner who can explain every failed row to finance without opening three tools. Treat the generator like payroll—silent success, loud failures, zero mystery duplicates in numbering or filenames.
Where DocForge for Salesforce fits
DocForge for Salesforce ships a Flow-callable invocable action with the interface above, a documented Apex API, structured errors, idempotency, and bulk support. Sign in and wire your first record-triggered flow in a sandbox.
Related articles
Salesforce Documents
From Salesforce Opportunity to Branded PDF Proposal in One Click
The reliable way to turn Opportunity line items into a branded proposal PDF attached back to the record—without exporting to Word or pasting into PandaDoc.
Salesforce Documents
EU Invoices in Salesforce: ZUGFeRD & Factur-X Without Conga
How to produce compliant ZUGFeRD/Factur-X hybrid PDF/XML invoices straight from a Salesforce Opportunity—what the standards require and what most orgs get wrong.
Salesforce Documents
Replacing Conga Composer in Salesforce: When and How
Conga is powerful and expensive. The cases where it's still the right call—and the ones where a focused alternative ships faster, costs less, and reduces admin pain.