Skip to main content

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

How to: Switch between a mail merge template and the result document

var commandId = "MailMergeSwitch";
var showMailMergeResult = false;
var templateDocument = null;
var format = DevExpress.RichEdit.DocumentFormat.OpenXml;

var newDataSource = [
    { firstName: "Alex", birthYear: 1991 },
    { firstName: "Joe", birthYear: 1990 },
    { firstName: "Bob", birthYear: 1995 }
];
var showTemplateDocument = function() {
    showMailMergeResult = !showMailMergeResult;
    richEdit.openDocument(templateDocument, "TemplateDocument", format);
};
var showResultDocument = function() {
    richEdit.loadingPanel.show();
    richEdit.exportToBase64(function(documentAsBase64) {
        templateDocument = documentAsBase64;
        richEdit.mailMerge(function (mergedDocument) {
          var reader = new FileReader();
          reader.onloadend = function () {
            showMailMergeResult = !showMailMergeResult;
            richEdit.openDocument(reader.result, "MergedDocument", format);
          };
          reader.readAsDataURL(mergedDocument);
        }, DevExpress.RichEdit.MergeMode.NewParagraph, format);
    });
};

richEdit.events.customCommandExecuted.addHandler(function(s, e) {
    if (e.commandName == commandId)
        if (showMailMergeResult)
            showTemplateDocument();
        else 
            showResultDocument();
});

richEdit.newDocument();
richEdit.document.insertText(richEdit.document.length, 'You can change template as you want.');
richEdit.document.insertParagraph(richEdit.document.length);
richEdit.document.insertText(richEdit.document.length, 'FirstName: ');
richEdit.document.fields.createMergeField(richEdit.document.length, "firstName").update();
richEdit.mailMergeOptions.setDataSource(newDataSource);

richEdit.documentName = "TemplateDocument";

richEdit.updateRibbon(function(ribbon) {
    if (!ribbon.getTab(DevExpress.RichEdit.RibbonTabType.MailMerge).getItem(commandId))
        ribbon.getTab(DevExpress.RichEdit.RibbonTabType.MailMerge)
            .insertItem(new DevExpress.RichEdit.RibbonButtonItem(commandId, "Switch document"), 0);
    ribbon.activeTabIndex = DevExpress.RichEdit.RibbonTabType.MailMerge;
});