LWC Word Document Generation Examples

Scenario

Generate DOCX files from Salesforce data using LWC + Apex, then store output in Salesforce Files.

Architecture Pattern

  1. LWC triggers Apex with record context.
  2. Apex gathers data and sends template payload to external DOCX renderer.
  3. Apex stores returned bytes as ContentVersion.
  4. 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

Security Notes