# pdf-viewer-semantic-text-comparison

> Compare two selected PDF files with semantic text comparison, synchronized scrolling, highlighted changes, and a difference panel.

**Framework:** react  **Component:** PdfViewer  **Variant:** semantic-text-comparison

## 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/react/ts/pdf-viewer-semantic-text-comparison.json
```

**Install Package(s)**

```bash
npm install @syncfusion/ej2-react-pdfviewer
```

**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/pdf-viewer-semantic-text-comparison/PdfViewer.tsx

```tsx
import { useEffect, useRef, useState } from 'react';
import {
    PdfComparerComponent, TextComparisonOptions,
    type PdfComparerComponent as PdfComparerComponentType
} from '@syncfusion/ej2-react-pdfviewer';

type ComparisonDocuments = {
    original: string;
    modified: string;
    id: number;
};

const resourceUrl = 'https://cdn.syncfusion.com/ej2/35.1.37/dist/ej2-pdfviewer-lib';
const comparisonOptions = {
    beforeColor: '#FF0000',
    afterColor: '#00FF00',
    beforeColorOpacity: 0.4,
    afterColorOpacity: 0.4,
    enableHighlights: true
} as TextComparisonOptions;

function SemanticTextComparison() {
    const comparerRef = useRef<PdfComparerComponentType | null>(null);
    const originalInputRef = useRef<HTMLInputElement | null>(null);
    const modifiedInputRef = useRef<HTMLInputElement | null>(null);
    const comparisonId = useRef(0);
    const [originalFile, setOriginalFile] = useState<File | null>(null);
    const [modifiedFile, setModifiedFile] = useState<File | null>(null);
    const [comparisonDocuments, setComparisonDocuments] = useState<ComparisonDocuments | null>(null);
    const [isComparing, setIsComparing] = useState(false);
    const [statusMessage, setStatusMessage] = useState('Choose two PDF files to compare.');

    useEffect(() => {
        const comparer = comparerRef.current;
        if (!comparisonDocuments || !comparer) {
            return;
        }

        let isCurrentComparison = true;
        const runComparison = async () => {
            try {
                await comparer.compare();
                if (isCurrentComparison) {
                    setStatusMessage('Comparison requested. Review the highlighted changes in both viewers and the difference panel.');
                }
            } catch (error) {
                console.error('Unable to compare the selected PDF documents.', error);
                if (isCurrentComparison) {
                    setStatusMessage('Unable to compare the selected PDFs. See the browser console for details.');
                }
            } finally {
                if (isCurrentComparison) {
                    setIsComparing(false);
                }
            }
        };

        void runComparison();
        return () => {
            isCurrentComparison = false;
            URL.revokeObjectURL(comparisonDocuments.original);
            URL.revokeObjectURL(comparisonDocuments.modified);
        };
    }, [comparisonDocuments]);

    const selectFile = (
        file: File | undefined,
        setSelectedFile: (value: File | null) => void,
        inputRef: React.RefObject<HTMLInputElement | null>
    ) => {
        if (!file) {
            return;
        }
        if (!file.name.toLowerCase().endsWith('.pdf')) {
            setStatusMessage('Select a file with the .pdf extension.');
            if (inputRef.current) {
                inputRef.current.value = '';
            }
            return;
        }

        setSelectedFile(file);
        setComparisonDocuments(null);
        setIsComparing(false);
        setStatusMessage('PDF selected. Choose the other document or compare the selected files.');
    };

    const clearFile = (
        setSelectedFile: (value: File | null) => void,
        inputRef: React.RefObject<HTMLInputElement | null>
    ) => {
        setSelectedFile(null);
        setComparisonDocuments(null);
        setIsComparing(false);
        if (inputRef.current) {
            inputRef.current.value = '';
        }
        setStatusMessage('Choose two PDF files to compare.');
    };

    const compareDocuments = () => {
        if (!originalFile || !modifiedFile) {
            return;
        }

        setIsComparing(true);
        setStatusMessage('Loading PDF documents for comparison...');
        let originalUrl: string | null = null;
        try {
            originalUrl = URL.createObjectURL(originalFile);
            const modifiedUrl = URL.createObjectURL(modifiedFile);
            setComparisonDocuments({
                original: originalUrl,
                modified: modifiedUrl,
                id: ++comparisonId.current
            });
        } catch (error) {
            if (originalUrl) {
                URL.revokeObjectURL(originalUrl);
            }
            console.error('Unable to prepare the selected PDF files for comparison.', error);
            setIsComparing(false);
            setStatusMessage('Unable to prepare the selected PDFs. Please try selecting them again.');
        }
    };

    return (
        <div className='control-section'>
            <div
                role='group'
                aria-label='PDF comparison files'
                style={{
                    display: 'flex',
                    alignItems: 'flex-end',
                    flexWrap: 'wrap',
                    gap: '12px',
                    marginBottom: '12px'
                }}
            >
                <div style={{ minWidth: '260px', flex: '1 1 260px' }}>
                    <label htmlFor='original-pdf-file' style={{ display: 'block', marginBottom: '4px' }}>
                        Original document
                    </label>
                    <input
                        id='original-pdf-file'
                        ref={originalInputRef}
                        className='e-input'
                        type='file'
                        accept='.pdf,application/pdf'
                        onChange={(event) => selectFile(
                            event.currentTarget.files?.[0],
                            setOriginalFile,
                            originalInputRef
                        )}
                    />
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>
                        <span>{originalFile?.name ?? 'Choose a PDF file'}</span>
                        {originalFile && (
                            <button
                                className='e-btn'
                                type='button'
                                onClick={() => clearFile(setOriginalFile, originalInputRef)}
                            >
                                Remove
                            </button>
                        )}
                    </div>
                </div>
                <div style={{ minWidth: '260px', flex: '1 1 260px' }}>
                    <label htmlFor='modified-pdf-file' style={{ display: 'block', marginBottom: '4px' }}>
                        Modified document
                    </label>
                    <input
                        id='modified-pdf-file'
                        ref={modifiedInputRef}
                        className='e-input'
                        type='file'
                        accept='.pdf,application/pdf'
                        onChange={(event) => selectFile(
                            event.currentTarget.files?.[0],
                            setModifiedFile,
                            modifiedInputRef
                        )}
                    />
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>
                        <span>{modifiedFile?.name ?? 'Choose a PDF file'}</span>
                        {modifiedFile && (
                            <button
                                className='e-btn'
                                type='button'
                                onClick={() => clearFile(setModifiedFile, modifiedInputRef)}
                            >
                                Remove
                            </button>
                        )}
                    </div>
                </div>
                <button
                    className='e-btn e-primary'
                    type='button'
                    onClick={compareDocuments}
                    disabled={!originalFile || !modifiedFile || isComparing}
                >
                    {isComparing ? 'Comparing...' : 'Compare'}
                </button>
            </div>
            <p role='status' aria-live='polite'>{statusMessage}</p>
            {comparisonDocuments && (
                <div style={{ height: '640px', width: '100%' }}>
                    <PdfComparerComponent
                        key={comparisonDocuments.id}
                        ref={comparerRef}
                        resourceUrl={resourceUrl}
                        comparisonOptions={comparisonOptions}
                        originalDocumentPath={comparisonDocuments.original}
                        modifiedDocumentPath={comparisonDocuments.modified}
                        enableDifferencePanel={true}
                        enableSyncScrolling={true}
                        height='640px'
                        width='100%'
                    />
                </div>
            )}
        </div>
    );
}

export default SemanticTextComparison;

```
