Show Word Document in HTML Page Using JavaScript



To show a word document in an HTML page using JavaScript is important where you are required to read Word documents within your browser. This article will discuss two approaches to accomplishing this in JavaScript. They both allow you to teach your application how to load.docx files and display them on your webpage to the user.

In this article, our task is to show a word document in an HTML page using JavaScript. We will be either using a .docx file from our system or using URL.

Approaches to Show a Word Document in HTML

1. Using Mammoth.js Library

Mammoth.js is a JavaScript library for converting.docx files to clean HTML and thereby rendering Word documents on your web page. This approach requires the Word document to be read and then converted to HTML so that its content can be shown on the page itself.

  • js ? This library parses.docx files into HTML as an ArrayBuffer and parses the content into a structured HTML block.
  • FileReader API ? To read the selected Word document as ArrayBuffer is required by Mammoth.js for the conversion.
  • Displaying Content ? After the conversion is complete the content is shown within the div with id="displayArea".

Example

Following is the given code for displaying Word Documents using Mammoth.js.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display DOCX File in HTML</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.2/mammoth.browser.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" accept=".docx" />
  <div id="displayArea"></div>
<script>
document.getElementById('fileInput').addEventListener('change', function (event) {
   const fileReader = new FileReader();
   fileReader.onload = function (loadEvent) {
      const arrayBuffer = loadEvent.target.result;
      // Convert the DOCX file to HTML using Mammoth
      mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
      .then(function (resultObject) { // Display the converted content
         document.getElementById('displayArea').innerHTML = resultObject.value;
      })
      .catch(function (error) {
         console.error("Conversion error: ", error);
      });
   };
   // Read the file as ArrayBuffer
   fileReader.readAsArrayBuffer(event.target.files[0]);
});
</script>
</body>
</html>

2. Using iFrame with Microsoft Office Viewer

A way to show .docx files directly in a browser is by using an embedded Microsoft Office Viewer. This method does not entail reading documents or converting them; rather, you can simply ?place' the document within your page, in an iframe.

Example

Following is the given code for enabling the users to view Word documents.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microsoft Office Viewer</title>
</head>
<body>
<h1>View Word Document</h1>
<iframe id="docFrame" style="width:100%; height:600px;" src=""></iframe>
<input type="text" id="fileUrl" placeholder="Enter the URL of the .docx file" />
<button id="loadFile">Display Document</button>
<script>
   document.getElementById('loadFile').addEventListener('click', function () {
      let docUrl = document.getElementById('fileUrl').value;
      let officeViewerUrl = `https://view.officeapps.live.com/op/embed.aspx?src=${docUrl}`;
      document.getElementById('docFrame').src = officeViewerUrl;
   });
</script>
</body>
</html>

3. View PDF in HTML using Javascript

JavaScript has provided several ways to embed pdf in HTML webpage, and one of the best ways was using the PDF.js which makes the PDFs to be rendered on the HTML canvas tag. The tutorial below demonstrates the creation of a basic file upload facility to display a PDF on your web page.

That is why, below is a typical approach of progressing through employing PDF.js to render a PDF file on an HTML page.

  • File Upload ? The user then inputs a PDF file using the <input type="file" /> function. The accept=".pdf" attribute makes it possible to upload only that kind of file.
  • FileReader API ? JavaScript's FileReader API reads the selected file as an ArrayBuffer that is necessary to process the binary data of the PDF.
  • js Library ? PDF.js parses the ArrayBuffer and the PDF document is loaded into the client using the pdfjsLib.getDocument() method.
  • Rendering the PDF ? An instance of pdf is created, and pdf.getPage(1) is used to give the first page of the document, Then the render() function is used to display the content of the PDF on an HTML canvas.
  • Canvas ? The canvas element which is an HTML element is used in the drawing surface upon which the PDF page is displayed. The height and width of the ?canvas' are set to the width and height of the scenes with respect to the viewport of the PDF page.

Example

Following is the given code for Displaying a PDF in an HTML format using JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display PDF in HTML</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
</head>
<body>
<h1>PDF Viewer</h1>
<input type="file" id="uploadFile" accept=".pdf" />
<canvas id="pdfCanvas" style="width:100%;"></canvas>
<script>
   document.getElementById('uploadFile').addEventListener('change', function (event) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = function () {
         const pdfData = new Uint8Array(reader.result);
         // Load PDF document using PDF.js
         pdfjsLib.getDocument(pdfData).promise.then(function (pdf) {
            // Fetch the first page of the PDF
            pdf.getPage(1).then(function (page) {
               const scale = 1.5;
               const viewport = page.getViewport({ scale: scale });
               const canvas = document.getElementById('pdfCanvas');
               const context = canvas.getContext('2d');
               canvas.height = viewport.height;
               canvas.width = viewport.width;
               const renderContext = {
                  canvasContext: context,
                  viewport: viewport
               };
               // Render the PDF page
               page.render(renderContext);
            });
         }).catch(function (error) {
            console.error('Error rendering PDF:', error);
         });
      };
      // Read the uploaded PDF file
      reader.readAsArrayBuffer(file);
   });
</script>
</body>
</html

Conclusion

In this article, we learned three approaches to embedding Word and PDF documents into HTML using JavaScript. We discussed how to convert DOCX files to HTML with the help of Mammoth.js, how to display DOCX files by their URLs with the help of iFrame and Microsoft Office Viewer, and how PDF files can be rendered directly with PDF.js. These approaches present a nice and convenient way of incorporating document viewing into Web apps without depending on third-party services.

Updated on: 2025-01-28T14:58:43+05:30

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements