# docx-editor-mail-merge

> Document editor mail merge sample generating personalized letters from template data.

**Framework:** javascript  **Component:** DocxEditor  **Variant:** mail-merge

## Get this item

**If you are an agent, fetch the JSON.** Source is inlined, so one request is enough and no tooling is required:

```
GET https://ai.syncfusion.com/r/javascript/docx-editor-mail-merge.json
```

**Install Package(s)**

```bash
npm install @syncfusion/ej2-documenteditor @syncfusion/ej2-lists @syncfusion/ej2-navigations @syncfusion/ej2-popups
```

**Notes**

- Syncfusion release: 2026 Volume 3 (v35.1.37)
- The Syncfusion package is licensed. The composition in this file is source you own and edit. See https://ai.syncfusion.com/licensing.md

## Source files

### src/components/docx-editor-mail-merge/docx-editor.html

```html
<div class="control-section" style="border-right: none;">
    <div id='documenteditor_titlebar' class="e-de-ctn-title"></div>
<div class="col-lg-2 property-section" style="padding-right: inherit;padding-left: 5px;height: 590px;border-left: 1px solid rgb(238, 238, 238);border-bottom:  1px solid rgb(238, 238, 238) ;"> 
   
    <h5><label style="display:block;margin:1px;padding-top: 18px;padding-top: 5px">Select Field to Insert</label></h5>
    <div id="listview" >
    </div>
</div>
<div class="col-lg-10 control-section" style='padding-left: 0px;padding-right: 0px;padding-top: 0px;'>
  <div id="container">
  </div>
</div>

<div class="overlay" id="popup-overlay" style="display: none;height: 590px;"></div>
    <div id='waiting-popup'>
        <svg class="circular" height="40" width="40">
            <circle class="circle-path" cx="25" cy="25" r="20" fill="none" stroke-width="6" stroke-miterlimit="10" />
        </svg>
    </div>
</div>

<style>
    .ej2-new {
        height: 590px;
    }
#documenteditor_titlebar {
    border-bottom: 1px solid #2B3481;
    height: 36px;
    line-height: 26px;
    width: 100%;
    font-size: 12px;
    padding-left: 15px;
    padding-right: 10px;
    font-family: inherit;
}

#documenteditor_title_contentEditor {
    height: 26px;
    max-width: 85%;
    width: auto;
    overflow: hidden;
    display: inline-block;
    padding-left: 4px;
    padding-right: 4px;
    margin: 5px;
}
.overlay {
    z-index: 10;
    display: none;
    position:relative;
    background-color: #383838;
    height: 100%;
    width: 100%;
    opacity: .5;
    cursor: not-allowed;
}
#waiting-popup {
    width: 56px;
    height: 56px;
    position: absolute;
    top: calc(50% - 28px);
    left: calc(50% - 28px);
    border-radius: 50%;
    padding: 3px;
    box-shadow: 0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12);
    overflow: hidden;
    background-position: center;
    background-color: white;
    z-index: 20;
    display: none;
}

.circular {
    animation: rotate 2s linear infinite;
    height: 50px;
    width: 50px;
    border-radius: 50%;
}

.circle-path {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
    animation: dash 1.5s ease-in-out infinite, color 6s ease-in-out infinite;
    stroke-linecap: round;
    stroke: #ff4081;
}

@keyframes rotate {
    100% {
        transform: rotate(360deg);
    }
}

@keyframes dash {
    0% {
        stroke-dasharray: 1, 200;
        stroke-dashoffset: 0;
    }

    50% {
        stroke-dasharray: 89, 200;
        stroke-dashoffset: -35;
    }

    100% {
        stroke-dasharray: 89, 200;
        stroke-dashoffset: -124;
    }
}

.single-line {
    cursor: text !important;
    outline: none;
}

.heading-section {
    padding-bottom: 20px;
    padding-top: 20px;
}

.single-line:hover {
    border-color: #e4e4e4 !important;
}

[contenteditable="true"].single-line {
    white-space: nowrap;
    border-color: #e4e4e4 !important;
}

/** Document editor sample level font icons*/
@font-face {
font-family: 'Font Mail merge icon';
src:
font-weight: normal;
font-style: normal;
}

[class^="sf-icon-"], [class*=" sf-icon-"] {
font-family: 'Font Mail merge icon' !important;
color: rgba(0, 0, 0, 0.54);
font-weight: 600;
font-size: 14px;
}
.sf-icon-FinishMerge:before { content: "\e700"; }
.sf-icon-InsertMergeField:before { content: "\e701"; }
@font-face {
    font-family: 'Sample brower icons';
    font-weight: normal;
    font-style: normal;
}
[class^="e-de-icon-"],
[class*=" e-de-icon-"] {
    font-family: 'Sample brower icons' !important;
}
.e-de-icon-Print:before {
    content: "\e723";
}

.e-de-icon-Download:before {
    content: "\e728";
}

/** sample level font icons ends*/
</style>
<script>
window.addEventListener("beforeunload", onbeforeunload);
function onbeforeunload() {
    return 'Want to save your changes?';
};
</script>

```

### src/components/docx-editor-mail-merge/docx-editor.ts

```typescript
import { DocumentEditorContainer, Toolbar } from '@syncfusion/ej2-documenteditor';
import { ListView, type SelectEventArgs } from '@syncfusion/ej2-lists';
import type { ClickEventArgs } from '@syncfusion/ej2-navigations/src/toolbar/toolbar';
import { Dialog, DialogUtility } from '@syncfusion/ej2-popups';
import { sfdtdata } from '../datasource/docx-editor-data';
/**
 * Default document editor sample
 */
// tslint:disable:max-func-body-length
export function initDocxEditorMailMerge(): void {
    let hostUrl: string = 'https://document.syncfusion.com/web-services/docx-editor/api/documenteditor/';
    let container: DocumentEditorContainer = new DocumentEditorContainer({ serviceUrl:hostUrl,enableToolbar: true, height: '590px',
     toolbarItems: [
            'New', 'Open', 'Separator', 'Undo',
            'Redo',
            'Separator',
            {
                prefixIcon: 'sf-icon-InsertMergeField',
                tooltipText: 'Insert Field',
                text: onWrapText('Insert Field'),
                id: 'InsertField'
            },
            {
                prefixIcon: 'sf-icon-FinishMerge',
                tooltipText: 'Merge Document',
                text: onWrapText('Merge Document'),
                id: 'MergeDocument'
            },
            'Separator',
            'Image',
            'Table',
            'Hyperlink',
            'Bookmark',
            'TableOfContents',
            'Separator',
            'Header',
            'Footer',
            'PageSetup',
            'PageNumber',
            'Break',
            'Separator',
            'Find',
            'Separator',
            'Comments',
            'TrackChanges',
            'Separator',
            'LocalClipboard',
            'RestrictEditing',
            'Separator',
            'FormFields',
            'UpdateFields',
        ],
        documentEditorSettings:{ showRuler: true}
    });
    DocumentEditorContainer.Inject(Toolbar);
    container.appendTo('#container');
    container.documentEditor.open(JSON.stringify({ sfdt: sfdtdata }));
    container.documentEditor.documentName = 'Mail Merge';
    container.documentChange = (): void => {
        container.documentEditor.focusIn();
    };
    function onWrapText(text: string): string {
        let content: string = '';
        let index: number = text.lastIndexOf(' ');
        content = text.slice(0, index);
        text.slice(index);
        content += '<div class="e-de-text-wrap">' + text.slice(index) + '</div>';
        return content;
    }
    container.toolbarClick = (args: ClickEventArgs): void => {
        switch (args.item.id) {
            case 'MergeDocument':
                mergeDocument();
                break;
            case 'InsertField':
                showInsertFielddialog();
                break;
        }
    };
    let waitingPopUp: HTMLElement;
    let inActiveDiv: HTMLElement;
    let listData: { [key: string]: Object }[] = [
        {
            text: 'ProductName',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'ShipName',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'CustomerID',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'Quantity',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'UnitPrice',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'Discount',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'ShipAddress',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'ShipCity',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'ShipCountry',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'OrderId',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        },
        {
            text: 'OrderDate',
            category: 'Drag or click the field to insert.',
            htmlAttributes: { draggable: true }
        }
    ];
    let listDivElement: HTMLElement = document.getElementById('listview');
    let listView: ListView = new ListView({
        dataSource: listData,
        fields: { tooltip: 'category' },
        select: onselect
    });
    listView.appendTo(listDivElement);
    document.getElementById('listview').addEventListener('dragstart', (event: any): void => {
        event.dataTransfer.setData('Text', event.target.innerText);
        event.target.classList.add('de-drag-target');
    });
    function onselect(args: SelectEventArgs): void {
        let fieldName: any = args.text;
        listView.selectItem(undefined);
        insertField(fieldName);
    }
    function insertField(fieldName: any): void {
        let fileName: any = fieldName.replace(/\n/g, '').replace(/\r/g, '').replace(/\r\n/g, '');
        let fieldCode: any = 'MERGEFIELD  ' + fileName + '  \\* MERGEFORMAT ';
        container.documentEditor.editor.insertField(fieldCode, '«' + fieldName + '»');
        container.documentEditor.focusIn();
    }

    // Prevent default drag over for document editor element
    document.getElementById('container').addEventListener('dragover', (event: any): void => {
        event.preventDefault();
    });

    // Drop Event for document editor element
    document.getElementById('container').addEventListener('drop', (e: any) => {
        let text: string = e.dataTransfer.getData('Text');
        container.documentEditor.selection.select({ x: e.offsetX, y: e.offsetY, extend: false });
        insertField(text);
    });

    document.addEventListener('dragend', (event: any) => {
        if (event.target.classList.contains('de-drag-target')) {
            event.target.classList.remove('de-drag-target');
        }
    });
    function showInsertFielddialog(): void {
        let instance: any = this;
        if (document.getElementById('insert_merge_field') === null || document.getElementById('insert_merge_field') === undefined) {
            let fieldcontainer: any = document.createElement('div');
            fieldcontainer.id = 'insert_merge_field';
            document.body.appendChild(fieldcontainer);
            insertFieldDialogObj.appendTo('#insert_merge_field');
            fieldcontainer.parentElement.style.position = 'fixed';
            fieldcontainer.style.width = 'auto';
            fieldcontainer.style.height = 'auto';
        }
        insertFieldDialogObj.close = (): void => { container.documentEditor.focusIn(); };
        insertFieldDialogObj.beforeOpen = (): void => { container.documentEditor.focusIn(); };
        insertFieldDialogObj.show();
        let fieldNameTextBox: any = document.getElementById('field_text');
        fieldNameTextBox.value = '';
    }
    function closeFieldDialog(): void {
        insertFieldDialogObj.hide();
        container.documentEditor.focusIn();
    }
    let insertFieldDialogObj: Dialog = new Dialog({
        header: 'Merge Field',
        content:
            '<div class="dialogContent">'
            // tslint:disable-next-line:max-line-length
            + '<label class="e-insert-field-label">Name:</label></br><input type="text" id="field_text" class="e-input" placeholder="Type a field to insert eg. FirstName">'
            + '</div>',
        showCloseIcon: true,
        isModal: true,
        width: 'auto',
        height: 'auto',
        close: closeFieldDialog,
        buttons: [
            {
                'click': (): void => {
                    let fieldNameTextBox: any = document.getElementById('field_text');
                    let fieldName: any = fieldNameTextBox.value;
                    if (fieldName !== '') {
                        container.documentEditor.editor.insertField('MERGEFIELD ' + fieldName + ' \\* MERGEFORMAT');
                    }
                    insertFieldDialogObj.hide();
                    container.documentEditor.focusIn();
                },
                buttonModel: {
                    content: 'Ok',
                    cssClass: 'e-flat',
                    isPrimary: true,
                },
            },
            {
                'click': (): void => {
                    insertFieldDialogObj.hide();
                    container.documentEditor.focusIn();
                },
                buttonModel: {
                    content: 'Cancel',
                    cssClass: 'e-flat',
                },
            },
        ],
    });

    function mergeDocument(): void {
        container.documentEditor.saveAsBlob('Docx').then((blob: Blob) => {
            let exportedDocumment: Blob = blob;
            let fileReader: any = new FileReader();
            fileReader.onload = (): void => {
                let base64String: any = fileReader.result;
                let responseData: any = {
                    fileName: container.documentEditor.documentName + '.docx',
                    documentData: base64String
                };
                waitingPopUp = document.getElementById('waiting-popup');
                inActiveDiv = document.getElementById('popup-overlay');
                showHideWaitingIndicator(true);
                let baseUrl: string = 'https://document.syncfusion.com/web-services/docx-editor/api/documenteditor/MailMerge';
                let httpRequest: XMLHttpRequest = new XMLHttpRequest();
                httpRequest.open('POST', baseUrl, true);
                httpRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
                httpRequest.onreadystatechange = () => {
                    if (httpRequest.readyState === 4) {
                        if (httpRequest.status === 200 || httpRequest.status === 304) {
                            container.documentEditor.open(httpRequest.responseText);
                        } else {
                            // Failed to merge document
                            DialogUtility.alert({
                                title: 'Information',
                                content: 'failure to merge document',
                                showCloseIcon: true,
                                closeOnEscape: true,
                            });
                        }
                        showHideWaitingIndicator(false);
                    }
                };
                httpRequest.send(JSON.stringify((<any>responseData)));
            };
            fileReader.readAsDataURL(blob);
        });
    }
    function showHideWaitingIndicator(show: boolean): void {
        inActiveDiv.style.display = show ? 'block' : 'none';
        waitingPopUp.style.display = show ? 'block' : 'none';
    }
}

```
