Display Files in the Document Viewer - React JS

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 (509 KB)
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 - React JS tutorial.

Make sure that Yarn is installed so that creating a React application can be done quickly via the command line. If yarn is not installed, it can be found on:

https://classic.yarnpkg.com/en/docs/install/#windows-stable

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 files are needed:

Make sure to copy these 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:

Note

Adding LEADTOOLS local references and setting a license are covered in more detail in the Add References and Set a License tutorial.

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.

<head> 
   <meta charset="utf-8" /> 
   <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> 
   <meta name="viewport" content="width=device-width, initial-scale=1" /> 
   <meta name="theme-color" content="#000000" /> 
   <meta 
      name="description" 
      content="Web site created using create-react-app" 
   /> 
   <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> 
   <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> 
   <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.ImageProcessing.Main.js"></script>   
   <script src="/common/Leadtools.ImageProcessing.Color.js"></script>   
   <script src="/common/Leadtools.ImageProcessing.Core.js"></script>   
   <script src="/common/Leadtools.ImageProcessing.Effects.js"></script>   
   <script src="/common/Leadtools.Document.js"></script>   
   <script src="/common/Leadtools.Document.Viewer.js"></script>  
   <script src="/common/ltlogic.js"></script> 
 
   <title>React App</title> 
</head> 

Add the Document Viewer Code

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

Open the App.js file in the src folder and replace the HTML with the following code:

import logo from './logo.svg'; 
import './App.css'; 
 
function App() { 
  return ( 
    <div className="App"> 
       
        <div className="container"> 
          <div className="toolbar"> 
            <div className="vcenter push-right"> 
              <label for="interactiveSelect">Interactive mode:</label> 
              <select id="interactiveSelect"></select> 
            </div> 
            <div className="vcenter push-right"> 
              <label for="annotationsSelect">Annotations objects:</label> 
              <select id="annotationsSelect"></select> 
            </div> 
            <div id="output" className="vcenter push-right"></div> 
            <div id="serviceStatus" className="vcenter push-right"></div> 
          </div> 
          <div className="docContainer"> 
            <div className="sidepanel" id="thumbnails"></div> 
            <div className="centerpanel" id="viewer"></div> 
            <div className="sidepanel" id="bookmarks"></div> 
          </div> 
        </div> 
       
    </div> 
  ); 
} 
 
export default App; 

Open the ltlogic.js file in a text editor. This file should be situated in the /public/common folder within the project structure. Creation of ltlogic.js is covered in the Add References and Set a License tutorial. Add a new class called ViewerInitializer after the set license call. Add the following code inside the new class.

class ViewerInitializer { 
   // Here is a constructor that takes a callback 
   constructor(callback) { 
      this.callback = callback; 
      this.init(); 
   } 
         
   static showServiceError(jqXHR, statusText, errorThrown) { 
      alert("Error returned from service. See the console for details."); 
      const serviceError = lt.Document.ServiceError.parseError(jqXHR, statusText, errorThrown); 
      console.error(serviceError); 
   } 
 
     
   // Init which just calls the initFactory() and testConnection() 
   init = () => { 
      this.initFactory(); 
      this.testConnection(); 
   } 
     
   // initFactory to set up service host, path, and api path 
   initFactory = () => { 
      lt.Document.DocumentFactory.serviceHost = "http://localhost:40000"; 
      lt.Document.DocumentFactory.servicePath = ""; 
      lt.Document.DocumentFactory.serviceApiPath = "api"; 
   } 
     
   // Test connection to document service using an element from html 
   testConnection = () => { 
      const serviceConnection = document.getElementById('serviceStatus'); 
      serviceConnection.innerHTML = "Connecting to: " + lt.Document.DocumentFactory.serviceUri; 
     
      lt.Document.DocumentFactory.verifyService() 
      .done((serviceRequest) => { 
         serviceConnection.innerHTML = "Successfully connected to: " + lt.Document.DocumentFactory.serviceUri; 
         this.createDocumentViewer(); 
      }) 
      .fail((jqXHR, statusText, errorThrown) => { 
         ViewerInitializer.showServiceError(jqXHR, statusText, errorThrown); 
         serviceConnection.innerHTML = "Service connection unavailable"; 
      }); 
   } 
     
   // Create document viewer function (LOOK AT DOCUMENTATION FOR THESE) 
   createDocumentViewer = () => {  
      // Initialize the user interface  
      const interactiveSelect = document.getElementById("interactiveSelect");  
              
      // Add the interactive commands that will be in the interactiveSelect dropdown  
      const panZoomOption = document.createElement("option");  
      panZoomOption.innerHTML = "Pan / Zoom";  
      panZoomOption.value = lt.Document.Viewer.DocumentViewerCommands.interactivePanZoom;  
      interactiveSelect.appendChild(panZoomOption);  
              
      const textOption = document.createElement("option");  
      textOption.value = lt.Document.Viewer.DocumentViewerCommands.interactiveSelectText;  
      textOption.innerHTML = "Select Text";  
      interactiveSelect.appendChild(textOption);  
              
      let documentViewer = null;  
      interactiveSelect.onchange = (e) => documentViewer.commands.run(e.target.value, null);  
              
      const annotationsSelect = document.getElementById("annotationsSelect");  
              
      // Add the annotations that will be in the annotationsSelect dropdown  
      const annSelectOption = document.createElement("option");  
      annSelectOption.innerHTML = "Select Annotations";  
      annSelectOption.value = lt.Annotations.Engine.AnnObject.selectObjectId.toString();  
      annotationsSelect.appendChild(annSelectOption);  
              
      const annLineOption = document.createElement("option");  
      annLineOption.innerHTML = "Line Object";  
      annLineOption.value = lt.Annotations.Engine.AnnObject.lineObjectId.toString();  
      annotationsSelect.appendChild(annLineOption);  
              
      const annRectOption = document.createElement("option");  
      annRectOption.innerHTML = "Rectangle Object";  
      annRectOption.value = lt.Annotations.Engine.AnnObject.rectangleObjectId.toString();  
      annotationsSelect.appendChild(annRectOption);  
              
      annotationsSelect.onchange = (e) => {  
         const value = +e.currentTarget.value;  
         documentViewer.annotations.automationManager.currentObjectId = value;  
      }  
              
      // Init the document viewer, pass along the panels  
      const createOptions = new lt.Document.Viewer.DocumentViewerCreateOptions();  
      // We are not going to use elements mode in this example  
      createOptions.viewCreateOptions.useElements = false;  
      createOptions.thumbnailsCreateOptions.useElements = false;  
              
      // The middle panel for the view  
      createOptions.viewContainer = document.getElementById("viewer");  
      // The left panel for the thumbnails  
      createOptions.thumbnailsContainer = document.getElementById("thumbnails");  
      // The right panel for the bookmarks  
      createOptions.bookmarksContainer = document.getElementById("bookmarks");  
      createOptions.useAnnotations = true;  
              
      // Create the document viewer  
      documentViewer = lt.Document.Viewer.DocumentViewerFactory.createDocumentViewer(createOptions);  
              
      // We prefer SVG viewing  
      documentViewer.view.preferredItemType = lt.Document.Viewer.DocumentViewerItemType.svg;  
              
      // Create html5 rendering engine  
      documentViewer.annotations.automationManager.renderingEngine = new lt.Annotations.Rendering.AnnHtml5RenderingEngine();  
      // Initialize documentViewer annotations  
      documentViewer.annotations.initialize();  
              
      documentViewer.annotations.automationManager.currentObjectIdChanged.add(function (sender, e) {  
         // When done drawing, the manager will return to the select object; so we need to force the annotationsSelect element to return to the select object option  
         annotationsSelect.value = sender.currentObjectId;  
      });  
              
      this.loadDefaultDoc(documentViewer, interactiveSelect)  
   }  
     
   // Load up a default document (LOOK AT DOCUMENTATION FOR THESE) 
 
   loadDefaultDoc = (viewer, interactiveSelect) => { 
      // Load a PDF document 
      const url = "https://demo.leadtools.com/images/pdf/leadtools.pdf"; 
      lt.Document.DocumentFactory.loadFromUri(url, null) 
      .done((doc) => { 
         const ready = () => { 
            viewer.setDocument(doc); 
            const panZoom = lt.Document.Viewer.DocumentViewerCommands.interactivePanZoom; 
            interactiveSelect.value = panZoom;  
            viewer.commands.run(panZoom, null); 
            if(this.callback) 
               this.callback(viewer); 
         } 
     
         if (doc.isStructureSupported && !doc.structure.isParsed){ 
            doc.structure.parse() 
            .done(ready) 
            .fail(ViewerInitializer.showServiceError); 
         } 
         else 
         { 
            ready(); 
         } 
                     
     
      }) 
      .fail(ViewerInitializer.showServiceError); 
   } 
} 
new ViewerInitializer(); 

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.

/*   
   Remove default body styling.   
   Set the body to flex as a column;   
*/   
body {   
  margin: 0;   
  display: flex;   
  flex-direction: column;   
}   
.container {   
  margin: 10px;   
  width: calc(100% - 20px);   
  height: calc(100vh - 20px);   
}   
.toolbar {   
  height: 5%;   
  width: 100%;   
  border-bottom: 2px solid #333;   
  flex-direction: row;   
  display: flex;   
}   
#bookmarks{   
  overflow: hidden;   
}   
.vcenter {   
  margin-top: auto;   
  margin-bottom: auto;   
}   
.hcenter{   
  margin-left: auto;   
  margin-right: auto;   
}   
.push-right{   
  margin-left: 10px;   
}   
.docContainer{   
  height: 95%;   
  width: 100%;   
  display: flex;   
  flex-direction: row;   
}   
.sidepanel{   
  width: 15%;   
  height: 100%;   
}   
  
.centerpanel{   
  width:100%;   
  height:100%;   
}   
 
/* Styles for Elements Mode. */   
.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 #6ecaab;   
  background-color: #b2decf;   
  padding: 10px;   
}   
.lt-image-border {   
  /* Image Border */   
  border: 3px solid #444;   
  background-color: white;   
}   
.lt-thumb-item {   
  /* Thumbnail Item */   
  border: 2px solid #6ecaab;   
  background-color: #b2decf;   
}   
.lt-thumb-item.lt-thumb-item-selected {   
  /* Selected Thumbnail Item */   
  border: 2px solid #59b2ba;   
  background-color: #8ce1e1;   
}   
.lt-thumb-item-hovered {   
  /* Hovered Thumbnail Item */   
  border: 2px solid #52b996;   
  background-color: #87c7b1;   
}   
.small-modal {   
  max-width: 200px;   
  width: 200px;   
} 

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>\LEADTOOLS22\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 yarn 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, view all the pages, and supports drawing annotations. To draw annotations, select one of the two annotation objects in the drop-down menu, then click and drag to draw the annotation object.

Wrap-Up

This tutorial showed how to initialize, load, and display a document into a DocumentViewer object. It also showed how to add Automated Annotations support.

See Also

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

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