# docx-editor-compare-documents

> Word editor compares uploaded original and revised documents and displays the revision results.

**Framework:** javascript  **Component:** DocxEditor  **Variant:** compare-documents

## 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-compare-documents.json
```

**Install Package(s)**

```bash
npm install @syncfusion/ej2-documenteditor @syncfusion/ej2-buttons
```

**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-compare-documents/docx-editor.html

```html
<div class="control-section">
    <!-- Controls container -->
    <div class="controls-container" style="width: 760px; margin: 10px auto">
      <!-- Files row -->
      <div class="files-row" style="display: flex; gap: 6px">
        <!-- Origial-->
        <div style="width: 360px; border-radius: 6px; padding: 14px; border: 1px dashed #ccc">
          <div style="display: flex; align-items: center; gap: 10px;">
            <span>Original document</span>
            <label style=" padding: 4px 10px;
              border: 1px solid #ccc;
              border-radius: 4px;
              cursor: pointer;">
            Choose file
            <input type="file" style="display: none;" id="originalFileInput" accept=".docx,.sfdt" />
            </label>
          </div>
          <!-- Filename + Delete icon -->
          <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 6px; font-size: 12px; color: #666;">
            <span id="originalFileName">Supported formats: SFDT, DOCX</span>
            <span id="removeOriginalFile" class="e-icons e-trash" style="cursor: pointer;" title="Remove file"></span>
          </div>
        </div>
        <!-- Revised file section-->
        <div style="width: 360px; border-radius: 6px; padding: 14px; border: 1px dashed #ccc;">
          <!-- Top row -->
          <div style="display: flex; align-items: center; gap: 10px;">
            <span>Revised document</span>
            <label style="
              padding: 4px 10px;
              border: 1px solid #ccc;
              border-radius: 4px;
              cursor: pointer;">
              Choose file
              <input type="file" style="display: none;" id="revisedFileInput" accept=".docx,.sfdt" />
            </label>
          </div>
          <!-- Filename + Delete icon -->
          <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 6px; font-size: 12px; color: #666;">
            <span id="revisedFileName">Supported formats: SFDT, DOCX</span>
            <span id="removeRevisedFile" class="e-icons e-trash" style="cursor: pointer;" title="Remove file"></span>
          </div>
        </div>
      </div>
      <!-- Checkbox, Compare & Download buttons  -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 12px;">  
        <!-- Checkbox -->
        <div class="actions-row">
          <label>
              <input type="checkbox" id="showResultCheckbox" checked="true" />
              Show comparison results with tracked changes
          </label>
        </div>
        <div style="display: flex; gap: 10px; margin-right: 32px;">
          <button class="e-primary" id="compareButton">Compare</button>
          <button class="e-outline e-flat e-primary" id="downloadButton">Download Result Document</button>
        </div>
      </div>
    </div>

    <!-- Editors Area -->
    <div style="display: flex; gap: 6px; height: calc(100vh - 330px); padding: 0px 10px;">
      <!-- Left Container -->
      <div style="width: 50%; display: flex; flex-direction: column; border: 1px solid #ddd; overflow: hidden;">
        <div style="padding: 8px; font-weight: 600;" class="e-de-ctn-title">Original Document</div>
        <div style="flex: 1; height: 100%;">
          <div id="editorContainer1"></div>
        </div>
      </div>
      <!-- Right Editor -->
      <div style="width: 50%; display: flex; flex-direction: column; border: 1px solid #ddd; overflow: hidden;">
        <div class="e-de-ctn-title" style="display: flex; justify-content: space-between; align-items: center">
          <div style="float: left; padding: 8px; font-weight: 600; flex: 1px;" id="rightEditorTitle" >
            Result Document (with tracked changes)
          </div>
          <button id="showRevisionsButton"
              class="e-de-ctn-title"
              iconCss="e-icons e-eye"
              style="float: right; font-weight: 400; background: transparent; box-shadow: none; border-color: transparent; border-radius: 0px;
                    color: inherit; font-size: 12px;"
              title="Show/Hide Revisions Pane">
              Show Review Pane
          </button>
        </div>
        <div style="flex: 1; height: 100%;">
          <div id="editorContainer2"></div>  
        </div>
      </div>
    </div>

    <!-- Waiting Popup Overlay -->
    <div class="overlay" id="popup-overlay"></div>
    <div id='waiting-popup' style="display: none;">
      <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>

    .overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(56, 56, 56, 0.5);
      z-index: 9999;
      display: none;
      cursor: not-allowed;
    }

    #waiting-popup {
      width: 56px;
      height: 56px;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      padding: 3px;
      background: white;
      box-shadow: 0px 3px 6px rgba(0,0,0,.3);
      z-index: 10000;
      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;
        }
    }
  </style>
```

### src/components/docx-editor-compare-documents/docx-editor.ts

```typescript
import { DocumentEditorContainer, Toolbar, DocumentEditor } from '@syncfusion/ej2-documenteditor';
import { Button } from '@syncfusion/ej2-buttons';
import * as data from '../datasource/docx-editor-data';
/**
 * Document Comparison sample
 */
export function initDocxEditorCompareDocuments(): void {
    let serviceUrl: string = 'https://document.syncfusion.com/web-services/docx-editor/api/documenteditor/';
    // Load necessary modules
    DocumentEditorContainer.Inject(Toolbar);
    
    // Document editor container references
    let editorContainer1: DocumentEditorContainer;
    let editorContainer2: DocumentEditorContainer;

    // Track files and state
    let originalFile: File | null = null;
    let revisedFile: File | null = null;
    let showResult: boolean = true;
    let compareClicked: boolean = false;
    let showRevisions: boolean = false;

    // Initialize the UI components after the DOM is fully loaded
    createDocumentEditors();
    attachEventListeners();

    function createDocumentEditors(): void {
        // Create the first document editor
        editorContainer1 = new DocumentEditorContainer({
            serviceUrl: serviceUrl,
            enableToolbar: false,
            showPropertiesPane: false,
            height: '100%',
            width: '100%'
        });
        editorContainer1.appendTo('#editorContainer1');

        // Create the second document editor
        editorContainer2 = new DocumentEditorContainer({
            serviceUrl: serviceUrl,
            enableToolbar: false,
            showPropertiesPane: false,
            height: '100%',
            width: '100%'
        });
        editorContainer2.appendTo('#editorContainer2');

        editorContainer1.documentEditor.open(JSON.stringify((<any>data).originalDocument));
        editorContainer2.documentEditor.showRevisions = false;
        editorContainer2.documentEditor.open(JSON.stringify((<any>data).revisedDocument));

        // Sync scroll between editors
        editorContainer1.documentEditor.viewChange = () => {
            const pos = editorContainer1.documentEditor.selection.getScrollPosition();
            editorContainer2.documentEditor.selection.setScrollPosition(pos);
        };

        editorContainer2.documentEditor.viewChange = () => {
            const pos = editorContainer2.documentEditor.selection.getScrollPosition();
            editorContainer1.documentEditor.selection.setScrollPosition(pos);
        };
    }

    function attachEventListeners(): void {
        // Get file input elements
        const originalFileInput = document.getElementById('originalFileInput') as HTMLInputElement;
        const revisedFileInput = document.getElementById('revisedFileInput') as HTMLInputElement;
        const showResultCheckbox = document.getElementById('showResultCheckbox') as HTMLInputElement;
        const removeOriginalFileSpan = document.getElementById('removeOriginalFile') as HTMLElement;
        const removeRevisedFileSpan = document.getElementById('removeRevisedFile') as HTMLElement;

        // Add event listners for clicking the remove icon for file names.
        removeOriginalFileSpan.addEventListener('click', (e: Event) =>{
            originalFile = null;
            compareClicked = false;
            updateButtonStates();
            setOringialFileName();
        });

        removeRevisedFileSpan.addEventListener('click', (e: Event) =>{
            revisedFile = null;
            compareClicked = false;
            updateButtonStates();
            setRevisedFileName();
        });
        
        // Add event listeners for file inputs
        originalFileInput.addEventListener('change', (e: Event) => {
            const input = e.target as HTMLInputElement;
            originalFile = input.files ? input.files[0] : null;
            compareClicked = false;
            updateButtonStates();
            setOringialFileName();
        });
        
        revisedFileInput.addEventListener('change', (e: Event) => {
            const input = e.target as HTMLInputElement;
            revisedFile = input.files ? input.files[0] : null;
            compareClicked = false;
            updateButtonStates();
            setRevisedFileName();
        });
        
        // Show result checkbox listener
        showResultCheckbox.addEventListener('change', (e: Event) => {
            const input = e.target as HTMLInputElement;
            showResult = input.checked;
            updateRightEditorTitle();
        });

        // Compare button
        const compareButton = new Button({
            cssClass: 'e-primary',
            disabled: true
        });
        compareButton.appendTo('#compareButton');

        // Download button
        const downloadButton = new Button({
            cssClass: 'e-outline e-flat e-primary',
            iconCss: 'e-icons e-download',
            disabled: true
        });
        downloadButton.appendTo('#downloadButton');

        const showRevisionsButton = new Button({
            iconCss: 'e-icons e-eye'
        });
        showRevisionsButton.appendTo('#showRevisionsButton');

        // Compare button click handler
        document.getElementById('compareButton')?.addEventListener('click', async () => {
            if (!originalFile || !revisedFile) return;

            var orginalFileFormatType = originalFile.name.slice(originalFile.name.lastIndexOf('.')).toLowerCase();
            var revisedFileFormatType = revisedFile.name.slice(revisedFile.name.lastIndexOf('.')).toLowerCase();
            if(isSupportedFormatType(orginalFileFormatType) && isSupportedFormatType(revisedFileFormatType)){

                compareClicked = true;
                showRevisions = false;
                showRevisionsButton.content = 'Show Review Pane';
                downloadButton.disabled = false;
                showHideWaitingIndicator(true);

                if (showResult) {
                    await openFileInEditor(originalFile, editorContainer1.documentEditor);
                    await loadComparedDocumentAndOpen(editorContainer2.documentEditor, originalFile, revisedFile);
                } else {
                    await openFileInEditor(originalFile, editorContainer1.documentEditor);
                    await openFileInEditor(revisedFile, editorContainer2.documentEditor);
                }

                updateRightEditorTitle();
                showHideWaitingIndicator(false);
            }
            else{
                alert('Unsupported file type is selected. Please use either .docx or .sfdt file.');
                compareButton.disabled = true;
                downloadButton.disabled = true;
            }
        });

        // Download button click handler
        document.getElementById('downloadButton')?.addEventListener('click', () => {
            if (editorContainer2.documentEditor) {
                editorContainer2.documentEditor.save('Result', 'Docx');
            }
        });

        document.getElementById('showRevisionsButton')?.addEventListener('click', () => {
            const editor2 = editorContainer2.documentEditor;
            if (editor2) {
                showRevisions = !showRevisions;
                editor2.showRevisions = showRevisions;
                showRevisionsButton.content = showRevisions ? 'Hide Review Pane' : 'Show Review Pane';
            }
        });
    }

    function updateButtonStates(): void {
        const compareButtonObj = (document.getElementById('compareButton') as any).ej2_instances[0];
        if (compareButtonObj) {
            compareButtonObj.disabled = !(originalFile && revisedFile);
        }

        const downloadButtonObj = (document.getElementById('downloadButton') as any).ej2_instances[0];
        if (downloadButtonObj) {
            downloadButtonObj.disabled = !compareClicked;
        }
    }

    function isSupportedFormatType(formatType: string): boolean {
        switch (formatType) {
            case '.docx':
            case '.sfdt':
                return true;
            default:
                return false;
        }
    }

    async function openFileInEditor(file: File, editor: DocumentEditor): Promise<void> {
        const formatType = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();
        if (formatType === '.sfdt') {
            const content = await readFileAsText(file);
            editor.showRevisions = false;
            editor.open(content);
        }
        else if (isSupportedFormatType(formatType)) {
            try {
                const formData = new FormData();
                formData.append('file', file);
                const response = await fetch(serviceUrl + 'Import', {
                    method: 'POST',
                    body: formData
                });

                const sfdtString = await response.text();
                let sfdtObject: any = null;
                try {
                    sfdtObject = JSON.parse(sfdtString);
                } catch (e) {
                    alert("Failed to process the compared document due to no valid JSON. Please try again.");
                }
                if (sfdtObject) {
                    editor.showRevisions = false;
                    editor.open(JSON.stringify(sfdtObject));
                } else {
                    alert("Unable to display the compared document. Please try again.");
                }
            } catch (e) {
                alert('This Compare Documents demo supports only DOCX and SFDT file formats. Please select a valid DOCX or SFDT document and try again.');
            }
        } else {
            alert('Unsupported file type. Please use .docx, or .sfdt file.');
        }
    }

    async function loadComparedDocumentAndOpen(editor: DocumentEditor, originalFile: File, revisedFile: File): Promise<void> {
        const formData = new FormData();
        formData.append("originalFile", originalFile);
        formData.append("revisedFile", revisedFile);
        formData.append("author", "Author");
        formData.append("dateTime", new Date().toISOString());
        try {
            const response = await fetch(serviceUrl + 'CompareDocuments', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                alert("Failed to compare the selected documents. Please try again."); 
                return;
            }

            const sfdtString = await response.text();
            try {
                const sfdtObject = JSON.parse(sfdtString);
                editor.showRevisions = false;
                editor.open(sfdtObject);
            } catch (e) {
                alert("The comparison could not be completed due to no valid JSON. Please try again.");
            }
        } catch (e) {
            alert('Error during document comparison.');
        }
    }

    function readFileAsText(file: File): Promise<string> {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = event => {
                resolve(event.target?.result as string);
            };
            reader.onerror = error => reject(error);
            reader.readAsText(file);
        });
    }

    function showHideWaitingIndicator(show: boolean): void {
        let waitingPopUp: HTMLElement | null = document.getElementById('waiting-popup');
        let inActiveDiv: HTMLElement | null = document.getElementById('popup-overlay');
        if (waitingPopUp && inActiveDiv){
            inActiveDiv.style.display = show ? 'block' : 'none';
            waitingPopUp.style.display = show ? 'block' : 'none';
        }
    }

    function updateRightEditorTitle(): void {
        const titleElement = document.getElementById('rightEditorTitle');
        if (titleElement) {
            titleElement.textContent = showResult ?
                'Result Document (with tracked changes)' :
                'Revised Document';
        }
        const showRevisionsElement = document.getElementById('showRevisionsButton');
        if(showRevisionsElement){
            showRevisionsElement.style.display = showResult ? 'block' : 'none';
        }
    }

    function setOringialFileName(): void {
        const originalFileNameElement = document.getElementById('originalFileName');
        if(originalFileNameElement)
        {
            if (originalFile) {
                const size = Math.round(originalFile.size / 1024);
                const originalFileName = `${originalFile.name} (${size} KB)`;
                originalFileNameElement.textContent = originalFileName;                
            }
            else {
                originalFileNameElement.textContent = "Supported formats: SFDT, DOCX";
            }
        }
    }

   function setRevisedFileName(): void {
        const revisedFileNameElement = document.getElementById('revisedFileName');
        if(revisedFileNameElement)
        {
            if (revisedFile) {
                const size = Math.round(revisedFile.size / 1024);
                const revisedFileName = `${revisedFile.name} (${size} KB)`;
                revisedFileNameElement.textContent = revisedFileName;            
            }
            else {
                revisedFileNameElement.textContent = "Supported formats: SFDT, DOCX";
            }
        }
    }
}
```
