Display Files in the Document Viewer - ReactJS

This tutorial shows how to load and display files in the Document Viewer in a React JS application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to load files into a DocumentViewer object in a React JS.
application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (1 MB)
Platform React JS Web Application
IDE Visual Studio : Service \ Visual Studio Code : Client
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Display Files in the Document Viewer - ReactJS tutorial.

Get Started

Start by creating a template of the project by running the following command in a terminal npx create-react-app tutorialname --template typescript. This command will create the project folder and subfolders necessary to build the project.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have a copy of that tutorial project, follow the steps inside that tutorial to create it.

The references needed depend upon the purpose of the project. For this project, the following JS and TS files are needed:

Make sure to copy the JS files to the public\Common folder and import them in the public\index.html file.

For more information on which files to include for your JavaScript application, see Files to be Included with your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Import LEADTOOLS Dependencies

Open the index.html file in the public folder and add the below necessary script tags inside the head to import LEADTOOLS dependencies.

<html lang="en"> 
    <head> 
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> 
        <script src="/Common/Leadtools.js"></script> 
        <script src="/Common/Leadtools.Controls.js"></script> 
        <script src="/Common/Leadtools.Annotations.Engine.js"></script> 
        <script src="/Common/Leadtools.Annotations.Designers.js"></script> 
        <script src="/Common/Leadtools.Annotations.Rendering.Javascript.js"></script> 
        <script src="/Common/Leadtools.Annotations.Automation.js"></script> 
        <script src="/Common/Leadtools.Document.js"></script> 
        <script src="/Common/Leadtools.Document.Viewer.js"></script> 
 
        <title>Display Files in the Document Viewer</title> 
    </head> 
    <body> 
        <noscript>You need to enable JavaScript to run this app.</noscript> 
        <div id="root"></div> 
    </body> 
</html> 

Add the Document Viewer Code

With the project created, the references added, and the license set coding can begin.

Create a new folder named Components in the src folder and add two Typescript files named DocumentViewer.tsx and useToolbar.tsx. Insert the following code into the DocumentViewer.tsx file:

///<reference path="../../public/Common/Leadtools.d.ts"/> 
///<reference path="../../public/Common/Leadtools.Document.d.ts"/> 
///<reference path="../../public/Common/Leadtools.Document.Viewer.d.ts"/> 
///<reference path="../../public/Common/jquery.d.ts" /> 
import { useEffect, useRef, useState } from "react"; 
 
interface Props { 
    inputFile?: string; 
    interactiveMode: string; 
} 
 
function DocumentViewer({ inputFile, interactiveMode }: Props) { 
    const [documentViewer, setDocumentViewer] = useState<lt.Document.Viewer.DocumentViewer>(); 
    const viewer = useRef(null); 
    const thumbnail = useRef(null); 
 
    // On load connect to DocumentService and create DocumentViewer 
    useEffect(() => { 
        connectToDocumentService(); 
        createDocumentViewer(); 
    }, []); 
 
    // Update the document's file when a new file is uploaded 
    useEffect(() => { 
        updateDocumentViewer(); 
    }, [inputFile]); 
 
    // Update the DocumentViewer's interractive mode when a new one is selected 
    useEffect(() => { 
        updateDocumentInteractiveMode(); 
    }, [interactiveMode]); 
 
    async function updateDocumentViewer() { 
        if (documentViewer && inputFile) { 
            try { 
                const response = await fetch(inputFile); 
                const blob = await response.blob(); 
                const doc = await lt.Document.DocumentFactory.loadFromFile(blob, new lt.Document.LoadDocumentOptions()); 
                if (doc) { 
                    documentViewer.setDocument(doc); 
                } 
            } catch (error) { 
                console.log(error); 
            } 
        } 
    } 
 
    function updateDocumentInteractiveMode() { 
        documentViewer?.commands.run(interactiveMode, null); 
    } 
 
    async function connectToDocumentService() { 
        try { 
            lt.Document.DocumentFactory.serviceHost = "http://localhost:40000"; 
            lt.Document.DocumentFactory.servicePath = ""; 
            lt.Document.DocumentFactory.serviceApiPath = "api"; 
            await lt.Document.DocumentFactory.verifyService(); 
            console.log("Service Connection Verified!"); 
        } catch (error) { 
            console.error(error); 
            console.log("Service not properly connected."); 
        } 
    } 
 
    async function createDocumentViewer() { 
        try { 
            const createOptions = new lt.Document.Viewer.DocumentViewerCreateOptions(); 
            if (viewer.current && thumbnail.current) { 
                createOptions.viewContainer = viewer.current; 
                createOptions.thumbnailsContainer = thumbnail.current; 
                createOptions.viewCreateOptions.useElements = true; 
                createOptions.thumbnailsCreateOptions.useElements = false; 
                const docViewer = lt.Document.Viewer.DocumentViewerFactory.createDocumentViewer(createOptions); 
                docViewer.view.preferredItemType = lt.Document.Viewer.DocumentViewerItemType.image; 
                const url = "https://demo.leadtools.com/images/pdf/leadtools.pdf"; 
                const doc = await lt.Document.DocumentFactory.loadFromUri(url, new lt.Document.LoadDocumentOptions()); 
                if (doc) { 
                    docViewer.setDocument(doc); 
                    docViewer.commands.run(lt.Document.Viewer.DocumentViewerCommands.interactivePanZoom, null); 
                    setDocumentViewer(docViewer); 
                } 
            } 
        } catch (error) { 
            console.error(error); 
            console.log("DocumentViewer not created properly"); 
        } 
    } 
 
    return ( 
        <div className="container"> 
            <div id="thumbnail" ref={thumbnail} /> 
            <div id="viewer" ref={viewer} /> 
        </div> 
    ); 
} 
 
export default DocumentViewer; 

Then enter the following code in the useToolbar.tsx Typescript file:

import { ChangeEvent, useState } from "react"; 
 
function useToolbar() { 
    const [file, setFile] = useState<string>(); 
    const [interactiveMode, setInteractiveMode] = useState<string>(lt.Document.Viewer.DocumentViewerCommands.interactivePanZoom); 
 
    const handleFileUpload = (e: ChangeEvent<HTMLInputElement>) => { 
        if (e.target.files) { 
            const selectedFile = e?.target?.files[0]; 
            if (selectedFile) { 
                const newChosenFile = URL.createObjectURL(selectedFile); 
                setFile(newChosenFile); 
            } 
        } 
    }; 
 
    const handleDropDownChange = (button: string) => { 
        if (button === "selectText") { 
            setInteractiveMode(lt.Document.Viewer.DocumentViewerCommands.interactiveSelectText); 
        } else if (button === "panZoom") { 
            setInteractiveMode(lt.Document.Viewer.DocumentViewerCommands.interactivePanZoom); 
        } 
    }; 
 
    return { 
        file, 
        interactiveMode, 
        render: ( 
            <div className="Toolbar"> 
                <h2 className="Toolbar-title">LEADTOOLS Document Viewer</h2> 
                <div> 
                    <input type="file" onChange={handleFileUpload} /> 
                    <select onChange={(e) => handleDropDownChange(e.target.value)}> 
                        <option value="panZoom">Pan Zoom</option> 
                        <option value="selectText">Select Text</option> 
                    </select> 
                </div> 
            </div> 
        ), 
    }; 
} 
 
export default useToolbar; 

With the DocumentViewer and useToolbar code added, we can now add code to make the document viewer functional. Edit the existing App.tsx file to have the following code:

///<reference path="../public/Common/Leadtools.d.ts"/> 
import "./App.css"; 
import { useEffect } from "react"; 
import DocumentViewer from "./Components/DocumentViewer"; 
import useToolbar from "./Components/useToolbar"; 
 
function App() { 
    useEffect(() => { 
        init(); 
    }, []); 
 
    const { file, interactiveMode, render } = useToolbar(); 
 
    function init() { 
        const licenseUrl = "https://demo.leadtools.com/licenses/js/LEADTOOLSEVAL.txt"; 
        const developerKey = "EVAL"; 
        lt.RasterSupport.setLicenseUri(licenseUrl, developerKey, function (setLicenseResult) { 
            if (setLicenseResult.result) { 
                console.log("LEADTOOLS client license set successfully"); 
            } else { 
                const msg = "LEADTOOLS License is missing, invalid or expired\nError:\n"; 
                console.log(msg); 
                alert(msg); 
            } 
        }); 
    } 
 
    return ( 
        <> 
            {render} 
            <DocumentViewer inputFile={file} interactiveMode={interactiveMode} /> 
        </> 
    ); 
} 
 
export default App; 

Improve the Visuals of the Project

Navigate to App.css, in the src folder which creates our HTML elements. Add the following code to improve the visuals of the application.

html, 
body, 
#root { 
    height: 100%; 
    width: 100%; 
    background-color: darkgray; 
} 
 
body { 
    display: flex; 
    flex-direction: row; 
} 
 
.Toolbar { 
    display: flex; 
    flex-direction: row; 
    justify-content: space-between; 
    align-items: center; 
    column-gap: 10px; 
    padding-right: 50px; 
} 
 
.Toolbar-title { 
    text-align: center; 
    padding-left: 50px; 
} 
 
.container { 
    height: 98%; 
    width: 100%; 
    display: flex; 
    flex-direction: row; 
    background-color: lightgrey; 
} 
 
.selected { 
    background-color: #c9e0f7; 
} 
 
#viewer { 
    width: 90%; 
} 
 
#thumbnail { 
    width: 10%; 
} 
 
.lt-item, 
.lt-image-border { 
    /* Box Shadow (view, item, image border) */ 
    box-shadow: #333 2px 2px 5px 1px; 
} 
 
.lt-view, 
.lt-thumb-item { 
    /* View */ 
    margin: 5px; 
    padding: 5px; 
} 
 
.lt-item { 
    /* Item */ 
    border: 2px solid gray; 
    background-color: lightblue; 
    padding: 10px; 
} 
 
.lt-image-border { 
    /* Image Border */ 
    border: 3px solid #444; 
    background-color: white; 
} 

Run the Document Service

In order to run this application successfully, the LEADTOOLS .NET Framework Document Service is required. The LEADTOOLS .NET Framework Document Service project is located at <INSTALL_DIR>\LEADTOOLS23\Examples\Document\JS\DocumentServiceDotNet\fx.

Note: .NET FrameWork Document Service supports uploadDocumentBlob but .NET Core Document Service does not.

Open the DocumentService.csproj and run the project using IIS Express. After running the csproj Document Service project in Visual Studio, the webpage will show that the service is listening. The Client Side will be able to communicate with the Document Service, allowing the Image Data processing, and returning the OCR's text from the image.

Document service

Run the Project

To run the Document Viewer React application open a new terminal and cd into the root of the project. From there, run npm start. If you do not have the node modules included with the project, be sure to also run the command, npm install before running the project.

The application will run and open the browser. The DocumentViewer object appears and a sample PDF document indicated in the url variable passed into the loadFromUri function appears. This tutorial allows you to pan/zoom the document and view all the pages.

Wrap-Up

This tutorial showed how to initialize, load, and display a document into a DocumentViewer object.

See Also

Help Version 23.0.2024.4.23
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2024 LEAD Technologies, Inc. All Rights Reserved.


Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.