7.4 OmniStudio Document Generation & Dynamic PDF Production

Key Takeaways

  • OmniStudio Document Generation (DocGen) dynamically merges structured Salesforce CRM data into Microsoft Word (.docx) and PowerPoint (.pptx) templates to produce standardized, publication-quality government documents.
  • Client-Side Document Generation renders documents entirely within the constituent or caseworker's web browser, enabling interactive preview, instant PDF download, and zero server-side rendering queue overhead.
  • Server-Side Document Generation processes documents asynchronously via high-volume microservices, making it essential for automated batch processing, large multi-page documents (> 50 pages), and headless background Flows.
  • Template design relies on standardized token syntax, including simple value replacement ({{Field}}), conditional legal clauses ({#Condition}...{/Condition}), repeating section loops for line items, and dynamic image insertion.
  • Data Mappers (Extract and Transform) and Integration Procedures orchestrate multi-object data extraction, Business Rules Engine fee calculations, and payload restructuring before invoking DocGen rendering services.
Last updated: September 2026

7.4 OmniStudio Document Generation & Dynamic PDF Production

Exam Focus: Public agencies must issue thousands of legally binding, publication-quality official documents—building permits, business licenses, professional credentials, Notices of Funding Opportunity (NOFO) award letters, violation notices, and adverse action determinations. On the AP-222 examination, candidates must master OmniStudio Document Generation (DocGen), the critical architectural differences between Server-Side and Client-Side rendering engines, Microsoft Word (.docx) template authoring syntax (tokens, conditional sections, repeating tables), and end-to-end data orchestration using Data Mappers and Integration Procedures.


The Role of Document Generation in Public Sector Administration

In government operations, the culmination of regulatory licensing, grant allocations, or enforcement inspections is the generation of an official, immutable legal instrument. Examples include:

  • Official Licenses & Permits: A framed municipal restaurant health permit with watermarked agency seals, operational stipulations, and verification QR codes.
  • Notices of Funding Opportunity (NOFO) & Grant Agreements: Multi-page grant contracts detailing disbursement schedules, statutory compliance covenants, and audit reporting mandates.
  • Adverse Action & Violation Notices: Legally mandated notifications specifying regulatory code infractions, statutory appeal deadlines, and itemized penalty schedules.

Legacy agency systems generated these documents through manual word-processing mail merges or brittle third-party print drivers. This caused inconsistent legal wording, typographical errors in statutory citations, and untracked file dispersion. OmniStudio Document Generation (formerly Vlocity Document Generation) provides a unified, enterprise document engine natively integrated into Salesforce Public Sector Solutions.


Architectural Engine Comparison: Client-Side vs. Server-Side Document Generation

A fundamental architectural decision on the AP-222 exam is selecting between Client-Side and Server-Side Document Generation. Each engine serves distinct public sector operational scenarios:

┌─────────────────────────────────────────────────────────────────────────────┐
│                     Client-Side Document Generation                         │
├─────────────────────────────────────────────────────────────────────────────┤
│  • Execution Location: User Web Browser (V8 Engine / WebAssembly / pdfmake) │
│  • Trigger Mechanism: Interactive UI (OmniScript / Lightning Web Component) │
│  • Primary Use Case: Interactive preview, instant download, self-service    │
│  • Governance: Zero server queue, zero API calls, limited by browser memory │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                     Server-Side Document Generation                         │
├─────────────────────────────────────────────────────────────────────────────┤
│  • Execution Location: Asynchronous High-Volume DocGen Microservice         │
│  • Trigger Mechanism: Headless Flow, Integration Procedure, Apex, Batch     │
│  • Primary Use Case: Overnight batch renewal, large docs (> 50 pages), NOFO │
│  • Governance: Handled via asynchronous job queue; higher throughput limit  │
└─────────────────────────────────────────────────────────────────────────────┘

1. Client-Side Document Generation

Client-Side DocGen executes entirely inside the user's client browser using client-side JavaScript libraries (such as pdfmake wrapped in OmniStudio Lightning Web Components):

  • Interactive Visual Preview: The constituent or caseworker can preview the generated document directly inside the browser window, inspect merged fields, and make client-side adjustments before finalization.
  • Instant Constituent Download: Because rendering occurs locally, the constituent downloads the finalized PDF immediately without waiting in an asynchronous server queue.
  • Zero Server Compute Consumption: Document generation consumes zero Salesforce server CPU time and requires no external API callouts, making it highly cost-effective for high-volume public portals.
  • Architectural Limitations: Client-Side DocGen cannot execute in headless background processes (such as overnight batch Apex or record-triggered Flows) because it requires an active browser DOM. It is also limited by client device memory, making it unsuitable for massive documents (> 50–100 pages or > 10 MB).

2. Server-Side Document Generation

Server-Side DocGen delegates rendering to an asynchronous, high-volume cloud microservice managed by Salesforce:

  • Headless & Automated Execution: Server-Side DocGen can be invoked directly from automated Flows, Integration Procedures, scheduled batch jobs, or Apex triggers without any human user interface present.
  • Large & Complex Document Processing: The server-side rendering service effortlessly handles large documents (> 50 to 500 pages), complex multi-page nested tables, high-resolution vector municipal crests, and extensive legal addenda.
  • Batch Generation Pipelines: Ideal for scheduled administrative operations—such as generating 15,000 annual business license renewal certificates on the first of each month.
  • Architectural Considerations: Server-Side DocGen executes asynchronously. The initiating process receives a job ID and must poll or handle completion callbacks before retrieving the finalized ContentVersion record.

Template Authoring in Microsoft Word (.docx) & PowerPoint (.pptx)

Agencies design document templates using familiar enterprise authoring tools—primarily Microsoft Word (.docx) and Microsoft PowerPoint (.pptx). Designers author documents using standardized typographic styles, agency logos, and precise OmniStudio token tags.

1. Simple Value Replacement Tokens

To merge scalar CRM data into the document body, authors insert double-curly brace tokens corresponding to keys in the merged JSON payload:

This certifies that {{Account.Name}}, located at {{Application.SiteAddress}},
is hereby granted an official {{Application.LicenseType}} Permit.
Permit Identifier: {{Application.LicenseNumber}}
Effective Date:    {{Application.IssueDate | date:"MMMM d, yyyy"}}
Statutory Fee:     {{Application.TotalFee | currency:"USD"}}

DocGen supports dynamic formatting filters directly within the token syntax, ensuring dates, currency figures, and percentages format accurately without requiring pre-formatting in Apex.

2. Conditional Clauses & Regulatory Sections

Public sector documents frequently require conditional legal clauses that render only when specific regulatory criteria are met. Rather than authoring separate templates for every permit permutation, designers embed conditional block tags:

{#IsApproved}
SECTION 1: STATUTORY AUTHORIZATION
The Department of Public Health hereby authorizes the licensee to operate
a commercial food establishment in accordance with Municipal Code Title 14.
{/IsApproved}

{#^IsApproved}
SECTION 1: NOTICE OF ADVERSE ACTION & APPEAL RIGHTS
Your application has been DENIED for failure to meet structural ventilation
codes. Under Administrative Code Section 402, you have thirty (30) calendar
days from the date of this notice to file a formal administrative appeal.
{/^IsApproved}
  • {#PropertyName} ... {/PropertyName} renders the enclosed text only when PropertyName evaluates to true or is a non-empty list/object.
  • {#^PropertyName} ... {/^PropertyName} (inverted conditional) renders only when PropertyName is false, null, or absent.

3. Repeating Tables & Section Loops

Many public documents contain dynamic lists of indeterminate length—such as itemized inspection violations, permit fee breakdowns, or licensed facility staff rosters. Designers format these using repeating section loops inside Microsoft Word tables:

┌─────────────────┬───────────────────────────────────┬─────────────┐
│ Violation Code  │ Statutory Description             │ Fine Amount │
├─────────────────┼───────────────────────────────────┼─────────────┤
│ {#Violations}   │                                   │             │
│ {{Code}}        │ {{Description}}                   │ {{Fine}}    │
│ {/Violations}   │                                   │             │
└─────────────────┴───────────────────────────────────┴─────────────┘

When DocGen processes the template, it iterates through the Violations array in the JSON payload, dynamically expanding the Word table rows while preserving border styling, cell padding, and typography.

4. Dynamic Images & Verification QR Codes

DocGen supports dynamic image merging (such as caseworker signature stamps, agency crests, or verification QR codes) using the {%image_TokenName%} tag syntax. The JSON payload provides the image as a public URL, a Base64-encoded string, or a reference to a Salesforce ContentVersion record.


Data Orchestration: Data Mappers & Integration Procedures

Document generation requires gathering normalized relational data from multiple Salesforce tables (Accounts, Applications, Violations, Fees, Contacts) and restructuring it into a single, hierarchical JSON payload that matches the Word template's token schema.

┌─────────────────────────────────────────────────────────────────────────────┐
│                   OmniStudio Data Orchestration Pipeline                    │
├─────────────────────────────────────────────────────────────────────────────┤
│  1. Data Mapper Extract: Queries relational records across multiple objects │
│     • BusinessLicenseApplication, Account, Contact, RegulatoryCodeViolation │
│  2. Business Rules Engine (BRE) Expression Set:                             │
│     • Calculates statutory fee totals, expiration dates, penalty tier       │
│  3. Data Mapper Transform: Reshapes flat query rows into hierarchical JSON  │
│     • Structures arrays for {#Violations} and flags for {#IsApproved}       │
│  4. Integration Procedure (IP): Master controller orchestrating steps 1-3   │
│     • Calls OmniStudio Document Generation Service (Client-Side/Server-Side)│
│     • Receives generated ContentVersion ID & creates ContentDocumentLink    │
└─────────────────────────────────────────────────────────────────────────────┘

Step 1: Data Mapper Extract

The Data Mapper Extract queries database records across normalized relationships without custom SOQL coding:

  • Extract Step 1: Query BusinessLicenseApplication where Id = {ContextId}.
  • Extract Step 2: Query Account where Id = BusinessLicenseApplication.AccountId.
  • Extract Step 3: Query child RegulatoryCodeViolation records where InspectionId = BusinessLicenseApplication.InspectionId.

Step 2: Business Rules Engine & Calculations

The Integration Procedure passes extracted data into a BRE Expression Set. The rules engine evaluates statutory codes to determine whether compliance criteria were met, sets the boolean flag IsApproved = True/False, and calculates final fee totals.

Step 3: Data Mapper Transform

Templates expect clean, structured JSON hierarchies. The Data Mapper Transform reshapes flat extracted rows into nested token arrays:

{
  "Account": {
    "Name": "Apex Culinary Enterprises LLC",
    "SiteAddress": "400 Civic Center Plaza, Suite 200"
  },
  "Application": {
    "LicenseNumber": "PUB-2026-8841",
    "LicenseType": "Commercial Food Service",
    "IssueDate": "2026-09-04",
    "TotalFee": 1250.00
  },
  "IsApproved": true,
  "Violations": [
    {
      "Code": "SEC-14.2",
      "Description": "Improper cold food storage refrigeration temperature",
      "Fine": 250.00
    },
    {
      "Code": "SEC-18.9",
      "Description": "Missing secondary emergency fire exit signage",
      "Fine": 150.00
    }
  ]
}

Step 4: Invoking Document Generation Services

The Integration Procedure calls the native OmniStudio DocGen service action (docGenerationSample/generateDocument or OmniStudioDocGenService), passing the Template ID and the structured JSON payload. The service merges the data, converts the output into an immutable .pdf, and returns the ContentVersionId.


Document Conversion, Archival & Constituent Distribution

Once the document payload is merged, the platform manages the final conversion and security linkage:

  1. Conversion to Immutable PDF: While authoring occurs in .docx or .pptx, public agencies require immutable documents to prevent tampering. DocGen automatically converts the merged output into a high-fidelity PDF.
  2. ContentDocument & ContentVersion Creation: The generated PDF is committed to Salesforce Files. The system instantiates a ContentVersion record containing the PDF binary blob and creates the parent ContentDocument.
  3. Relational Linkage via ContentDocumentLink: Automation creates a ContentDocumentLink associating the file with the primary record (LinkedEntityId = Application.Id).
  4. Constituent Experience Cloud Distribution: The constituent accesses their Experience Cloud portal, where the generated permit or notice appears under their Official Documents tab for immediate download.

Comparison: Client-Side vs. Server-Side Document Generation

Architectural DimensionClient-Side Document GenerationServer-Side Document Generation
Rendering EnvironmentUser Web Browser (V8 JavaScript / pdfmake)High-Volume Cloud Microservice
Initiating ContextInteractive UI (OmniScript, FlexCard, LWC)Headless (Flow, Integration Procedure, Apex, Batch)
Visual Interactive PreviewSupported; users can preview and verify in browserNot supported interactively; produces file directly
Document Size & ComplexityBest for standard docs (< 50 pages, < 10 MB)Unlimited; handles massive documents (> 500 pages)
Batch Generation CapabilityNone; requires an active browser session per userExcellent; handles mass overnight batch runs
Server Compute OverheadZero server CPU time; zero Salesforce API consumptionConsumes asynchronous microservice execution bandwidth
Typical Public Sector Use CasesConstituent self-service permit download in portalOvernight license renewals, multi-page NOFO awards

💡 Real-World AP-222 Exam Scenarios & Case Analysis

Scenario 1: Overnight Automated Mass Renewal License Batch Generation

A state Board of Professional Licensing manages 120,000 active registered nurse licenses. Every year on December 1st, the board must generate renewed license certificate PDFs for all 18,000 nurses who completed mandatory continuing education and paid their renewal fees. The generation process must run overnight without caseworker interaction and attach each generated certificate to the nurse's Contact record.

Which Document Generation engine and integration pattern must the architect select?

  • The architect must select Server-Side Document Generation.
  • Client-Side generation is strictly invalid because it requires an active user web browser and cannot run in automated batch routines.
  • Configure a scheduled batch Apex job or scheduled Flow that queries eligible renewal records in batches.
  • The batch invokes an Integration Procedure that extracts nurse credential data via Data Mapper, calls the Server-Side DocGen service to merge the .docx license template into a PDF, and creates a ContentDocumentLink associating the certificate directly with the nurse's Contact record.

Scenario 2: Conditional Regulatory Enforcement Notice Generation

A municipal code enforcement agency issues inspection results letters to commercial property owners. If an inspection passes with zero infractions, the letter must display a 'Certificate of Compliance' congratulating the owner. If any infractions were discovered, the letter must omit the compliance certificate, display a bold 'Notice of Violation' header, render a formatted table of all cited infractions with individual fines, and include statutory administrative appeal instructions.

How should the architect design the document template to support both outcomes in a single file?

  • Design a single Microsoft Word (.docx) template rather than maintaining two separate templates.
  • Use conditional section tags {#HasViolations} ... {/HasViolations} around the violation header, citation table, and appeal rights text.
  • Use inverted conditional tags {#^HasViolations} ... {/^HasViolations} around the Certificate of Compliance congratulatory text.
  • Inside the violation section, create a Word table containing repeating loop tags {#Violations} {{Code}} | {{Description}} | {{Fine}} {/Violations}.
  • An Integration Procedure evaluates inspection results, sets HasViolations = true/false, constructs the Violations array, and passes the payload to DocGen.

Scenario 3: Real-Time Interactive Constituent Permit Preview and Download

A city planning portal allows residents to apply for residential tree-removal permits. Upon submitting the application and paying the $50 fee via an OmniScript, the constituent wants to immediately preview their temporary permit on screen and download the official PDF directly to their mobile device without waiting for an email notification.

What is the recommended OmniStudio configuration?

  • Configure Client-Side Document Generation within the OmniScript intake flow.
  • Add a Document Generation OmniScript step following the payment step.
  • The step invokes a Data Mapper Transform to format the user's input data into the template schema and utilizes client-side rendering to display an interactive PDF preview component.
  • The constituent reviews the rendered permit on-screen and clicks the native download button to save the PDF immediately, providing instant constituent gratification with zero server queuing latency.
Loading diagram...
OmniStudio Document Generation (DocGen) End-to-End Architecture
Test Your Knowledge

A state department of taxation must generate 45,000 annual property tax assessment notices every January. The process runs as an automated scheduled batch job overnight, merging complex multi-page property tax schedules, tax exemption line items, and payment stubs. Which OmniStudio Document Generation architecture must the enterprise architect implement?

A
B
C
D
Test Your Knowledge

An architect is designing a single Microsoft Word (.docx) template for regulatory code violation notices. If an inspection reveals infractions, the document must render a tabular list of all cited violations with individual penalty amounts. If no infractions were found, the table must be hidden and a compliance confirmation paragraph rendered instead. What is the correct template token syntax to achieve this?

A
B
C
D
Test Your Knowledge

A city planning department requires an automated solution where an approved building permit triggers the generation of an official permit PDF. The document must extract data from the Application, Account, and Inspection records, calculate statutory fee totals using agency business rules, merge the data into an approved Word template, and attach the resulting PDF to the Application record. What is the recommended OmniStudio orchestration pattern?

A
B
C
D