Import, Edit, and Save Documents with the Document Editor - HTML5 JavaScript

This tutorial shows how to embed the LEADTOOLS Document Editor into an application and use it to import, edit and export documents to PDF.

Overview  
Summary This tutorial covers how to embed a Document Editor into an application to import documents, edit them, then export to a PDF
Completion Time 20 minutes
Project Download tutorial project (2 KB)
Platform HTML5/JS
IDE Visual Studio Code/ Visual Studio 2019, 2022
Development License Download LEADTOOLS

Required Knowledge

Get familiar with the basic steps of creating a project and working with the Document Editor by reviewing the Add References and Set a License and Get Started with the Document Editor tutorials.

This tutorial makes use of http-server, a console command for running a static file server. To install http-server first install Node.js and then install http-server.

Be sure to download and install the LEADTOOLS SDK, and make sure that your license and key files are located in your <INSTALL_DIR>\LEADTOOLS22\Support\Common\License directory.

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 that project is unavailable, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added by .js files located at <INSTALL_DIR>\LEADTOOLS22\Bin\JS.

For this project, the following references are needed:

Make sure to copy these files to the project's lib folder.

For a complete list of which JS files are required for your application, refer to 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:

Write the HTML File

With the project created, dependencies added, and the license set, coding can begin. Open the index.html file located in the root folder and add the following HTML code to the head and the body to import the JS files and add the proper elements.

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <title> Import Edit and Save Documents with the Document Editor </title> 
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script> 
    <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> 
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> 
    <!--Import LEADTOOLS Dependencies--> 
    <script src="./lib/Leadtools.js"></script> 
    <script src="./lib/Leadtools.Annotations.Engine.js"></script> 
    <script src="./lib/Leadtools.Annotations.Automation.js"></script> 
    <script src="./lib/Leadtools.Document.js"></script> 
    <script src="./lib/Leadtools.Document.Editor.js"></script> 
    <!--Import Project Dependencies--> 
    <script src="./app.js"></script> 
    <link rel="stylesheet" href="style.css"> 
</head> 
<body> 
    <div> 
        <div id="title"> 
            Import Edit and Save Documents with the Document Editor 
        </div> 
        <ul id="menu"> 
            <li><a id="importBtn">Import Document</a></li> 
            <li><a id="exportBtn">Export as PDF</a> </li> 
        </ul> 
    </div> 
    <div id="editorWrapper" oncontextmenu="return false;"> 
        <div class="inner-body" id="content"> 
        </div> 
    </div> 
</body> 
</html> 

Write the CSS File

Open the style.css file located in the project folder and add the following styles.

html { 
    height: 100%; 
} 
 
body { 
    height: 100%; 
    margin: 0; 
    display: flex; 
    flex-direction: column; 
} 
 
#title { 
    padding: 10px; 
    font-size: 24px; 
} 
 
ul { 
    list-style-type: none; 
    margin: 0; 
    padding: 0; 
    overflow: hidden; 
} 
 
#editorWrapper { 
    border-top: 1px solid black; 
    height: 95%; 
} 
 
#content { 
    height: 100%; 
} 
 
li { 
    float: left; 
} 
 
li a { 
    display: block; 
    text-align: center; 
    padding: 14px 16px; 
    text-decoration: none; 
    margin-right: 10px; 
    margin-left: 10px; 
    cursor: pointer; 
    user-select: none; 
    font-weight: bold; 
} 
 
li:first-child { 
    border-right: 1px black solid; 
} 
 
li a:hover { 
    background-color: lightblue; 
} 

Write the JS File

Open the app.js file located in the project folder and add the below code to import, edit, and save documents using the Document Editor.

let editor = null; 
 
window.onload = () => { 
  setLicense(); 
  addEditControl(); 
  registerClickEvents(); 
  initFactory(); 
}; 
 
function addEditControl() { 
  const content = document.getElementById('content'); 
  editor = new lt.Document.Editor.DocumentEditor({ 
    root: content 
  }); 
} 
 
function registerClickEvents() { 
  document.getElementById('importBtn').onclick = selectAndLoadFile; 
  document.getElementById('exportBtn').onclick = exportAsPdf; 
} 
 
function setLicense() { 
  const licenseUrl = "./Leadtools/LEADTOOLS.lic.txt";  
  const developerKey = "ADD THE CONTENTS OF THE LEADTOOLS.lic.key.txt FILE";  
  lt.RasterSupport.setLicenseUri(licenseUrl, developerKey, function (  
    setLicenseResult  
  ) { 
    if (setLicenseResult.result) { 
      console.log("LEADTOOLS client license set successfully"); 
    } else { 
      const msg = "No LEADTOOLS License\n\nYour license file is missing, invalid or expired. LEADTOOLS will not function. Please contact LEAD Sales for information on obtaining a valid license."; 
      alert(msg); 
      const msgParagraph = document.createElement('p'); 
      msgParagraph.innerText = msg; 
      const parent = document.getElementById("div_container"); 
      while (parent.firstElementChild) { 
        parent.removeChild(parent.firstElementChild); 
      } 
      parent.appendChild(msgParagraph); 
      console.log(msg); 
    } 
  }); 
} 
 
function initFactory() { 
  // To communicate with the DocumentsService, it must be running!   
  // Change these parameters to match the path to the service.  
 
  lt.Document.DocumentFactory.serviceHost = "http://localhost:40000"; 
  lt.Document.DocumentFactory.servicePath = ""; 
  lt.Document.DocumentFactory.serviceApiPath = "api"; 
 
  // Set local proxy url template (Used in local load mode)  
  lt.Document.DocumentFactory.localProxyUrlTemplate = "http://localhost:40000/api/CorsProxy/Proxy?{0}"; 
 
  // Ping the Document service  
  lt.Document.DocumentFactory.verifyService() 
  try{ 
    async (response) => { 
      const serviceInfo = "Service name: '" + response.serviceName + "'"; 
      serviceInfo += " version: '" + response.serviceVersion + "'"; 
      serviceInfo += " platform: '" + response.servicePlatform + "'"; 
      serviceInfo += " OS: '" + response.serviceOperatingSystem + "'"; 
      lt.LTHelper.log(serviceInfo); 
    } 
  } catch { 
    async (jqXHR, statusText, errorThrown) => { 
      const errMsg = "Cannot reach the LEADTOOLS Document Service.\n\nPlease Make sure LEADTOOLS DocumentService is running\n - Examples/Document/JS/DocumentServiceDotNet\n - Examples/Document/JS/DocumentServiceJava\nand verify that the service path is correct, then refresh the application."; 
      window.alert(errMsg); 
      console.log(errMsg); 
    } 
  } 
} 
 
function selectAndLoadFile(){ 
  try { 
    const input = document.createElement('input'); 
    input.type = 'file'; 
    input.style.display = 'none'; 
    input.accept = '.doc, .docx, .pdf, .rtf, .txt'; 
 
    input.onchange = async (e) => { 
      const files = input.files; 
      if (!files || !files.length) 
        return; 
 
      const file = files[0]; 
      document.body.style.cursor = 'wait'; 
      try { 
        let doc = await lt.Document.Editor.EditableDocument.fromFile(file); 
        editor.setDocument(doc); 
      } finally { 
        document.body.style.cursor = 'default'; 
      } 
    }; 
    input.click(); 
  } catch (error) { 
    console.log(error); 
  } 
} 
 
async function exportAsPdf() { 
  try { 
    let doc = await editor.document.toFile("untitled", lt.Document.Writer.DocumentFormat.pdf); 
    doc.then(name => { }) 
  } catch { 
    console.log("File Exported Successfully") 
  } 
}  

Note

To export as DOCX or TXT simply change the second parameter of document.toFile to lt.Document.Writer.DocumentFormat.docx or lt.Document.Writer.DocumentFormat.txt.

Run the Project

Before running the application, run the Document Service. This tutorial relies on a server-side backend service for some of its functionality:

For instructions on how to set up and configure the Document Service, in the three platforms previously listed, refer to the steps in the Get Started with the Document Editor tutorial.

For the purposes of this tutorial, the .NET Framework Document Service is used and it can be found here: <INSTALL_DIR>\LEADTOOLS22\Examples\Document\JS\DocumentServiceDotNet\fx.

Open a terminal at the root folder (CMD, Powershell, or other) and type npm install http-server. This will add the static file hosting package mentioned earlier.

The server should start and run on http://localhost:8080. A message should appear in the console indicating all the ports that the server is available on.

Browse to the URL in a browser. To test the functionality of the menu, click the Import Document button and select a document to view in the editor.

Document importing

Then after it is loaded, click the Export as PDF to see it being saved to the desired location as a .pdf file type.

Document Exporting

Wrap-Up

This tutorial showed how to load, edit, and save documents using the LEADTOOLS Document Editor.

See Also

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

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