LWC Word Document Generation Examples
Scenario
Generate DOCX files from Salesforce data using LWC + Apex, then store output in Salesforce Files.
Architecture Pattern
- LWC triggers Apex with record context.
- Apex gathers data and sends template payload to external DOCX renderer.
- Apex stores returned bytes as
ContentVersion. - Optional: link file to parent record and notify user.
Example 1: LWC Trigger
import { LightningElement, api } from 'lwc';
import generateDoc from '@salesforce/apex/DocxService.generateDocument';
export default class DocxGenerator extends LightningElement {
@api recordId;
isRunning = false;
async handleGenerateDoc() {
this.isRunning = true;
try {
await generateDoc({ recordId: this.recordId });
} finally {
this.isRunning = false;
}
}
}
Example 2: Apex Service
public with sharing class DocxService {
@AuraEnabled
public static Id generateDocument(Id recordId) {
Account a = [SELECT Id, Name, Industry FROM Account WHERE Id = :recordId LIMIT 1];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:DocGenService/v1/render');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'templateKey' => 'account-summary',
'data' => new Map<String, Object>{
'name' => a.Name,
'industry' => a.Industry
}
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Doc generation failed: ' + res.getStatus());
}
ContentVersion cv = new ContentVersion(
Title = 'Account Summary - ' + a.Name,
PathOnClient = 'account-summary.docx',
VersionData = res.getBodyAsBlob()
);
insert cv;
return cv.Id;
}
}
Operational Notes
- Use Named Credentials for renderer authentication.
- Keep payload schema versioned so templates evolve safely.
- Capture renderer correlation IDs in logs for debugging.
- Enforce data minimization: send only fields required by template.
Security Notes
- Validate user access to the source record before generation.
- Avoid including sensitive fields unless required.
- Apply sharing settings on generated Files intentionally.