How to Display Word Document in HTML using JavaScript?
Last Updated :
18 Oct, 2024
Displaying Word documents in HTML is a valuable feature for web applications, enabling users to view content without needing to download files. JavaScript provides several tools and libraries to facilitate this process, making it easier to convert and render .docx files directly in the browser.
This capability is particularly useful for educational platforms, document management systems, and collaborative tools. Ultimately, integrating Word document display functionality can significantly improve content accessibility on the web.
These are the different approaches to displaying Word documents in HTML using JavaScript:
Using a File Upload and Viewer Library
One of the simplest methods is to use a library that can read and render Word documents in HTML. Libraries like mammoth.js can convert .docx files into HTML, making it easy to display the content in a web application. This approach typically involves a file upload interface where users can select their Word documents. After the file is uploaded, mammoth.js processes the document and transforms its content into a clean HTML format. This method is easy and requires minimal setup, allowing developers to quickly integrate document viewing capabilities into their applications.
How It Works:
- The user uploads a .docx file.
- The FileReader API reads the file.
- Mammoth.js converts the document into HTML and displays it in a <div>.
Example: Below is an example using a file upload and viewer library.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Display Word Document</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.2/mammoth.browser.min.js"></script>
</head>
<body>
<input type="file" id="upload" accept=".docx" />
<div id="output"></div>
<script>
document.getElementById('upload').addEventListener('change', function (event) {
let reader = new FileReader();
reader.onload = function (event) {
mammoth.convertToHtml({ arrayBuffer: event.target.result })
.then(function (result) {
document.getElementById('output').innerHTML = result.value;
})
.catch(function (err) {
console.log(err);
});
};
reader.readAsArrayBuffer(event.target.files[0]);
});
</script>
</body>
</html>
Output:
Using Google Docs Viewer
Using Google Docs Viewer offers a convenient way to display documents without needing to manage the file directly. This method allows you to embed the viewer into your webpage, enabling users to access the document seamlessly. It supports various file formats and ensures that the document appears consistent across different devices and browsers. Additionally, leveraging Google Docs Viewer means you don’t have to worry about document compatibility issues, making it an efficient option for quick sharing.
How It Works:
- The user enters a URL of a publicly accessible .docx file.
- Clicking the "Load Document" button sets the src of an iframe to the Google Docs viewer URL.
Example: Below is an example using Google docs viewer.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Google Docs Viewer</title>
</head>
<body>
<h1>View Word Document</h1>
<iframe id="docViewer" style="width:100%; height:600px;" src=""></iframe>
<input type="text" id="urlInput" placeholder="Enter URL of .docx file" />
<button id="loadDoc">Load Document</button>
<script>
document.getElementById('loadDoc').addEventListener('click', function () {
let url = document.getElementById('urlInput').value;
let viewerUrl = `https://docs.google.com/gview?url=${url}&embedded=true`;
document.getElementById('docViewer').src = viewerUrl;
});
</script>
</body>
</html>
Output:
Converting Word Document to PDF First
Converting your Word document to a PDF before displaying it can streamline the process and enhance compatibility across different platforms. PDF files maintain formatting, ensuring that your document looks exactly as intended, regardless of the viewer's software. Using a tool like PDF.js allows for smooth integration within web applications, providing an interactive experience for users. This approach also minimizes potential issues with font rendering and layout changes that can occur when displaying Word documents directly.
How It Works:
- The user uploads a PDF file (converted from Word).
- PDF.js reads the PDF and renders the first page onto a canvas.
Example: Below is an example converting word document to PDF First:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>PDF Viewer</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
</head>
<body>
<input type="file" id="upload" accept=".pdf" />
<canvas id="pdfViewer" style="width:100%;"></canvas>
<script>
document.getElementById('upload').addEventListener('change', function (event) {
let file = event.target.files[0];
let fileReader = new FileReader();
fileReader.onload = function () {
let typedarray = new Uint8Array(this.result);
pdfjsLib.getDocument(typedarray).promise.then(function (pdf) {
pdf.getPage(1).then(function (page) {
let viewport = page.getViewport({ scale: 1 });
let canvas = document.getElementById('pdfViewer');
let context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
let renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
});
};
fileReader.readAsArrayBuffer(file);
});
</script>
</body>
</html>
Output:
Conclusion
While displaying Word documents directly in HTML requires some extra steps, using libraries like Mammoth.js or embedding solutions like Google Docs Viewer can simplify the process. Depending on your needs, you can choose the method that best fits your application.
Similar Reads
How to Add JavaScript in HTML Document?
To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file. Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other e
4 min read
How to use document.images in JavaScript ?
In JavaScript, the document.images property returns a collection of all "<img>" elements within the current document. We can manipulate these images using various properties and methods. We will see how to work with document.images in JavaScript. ApproachFirst, create a basic HTML structure an
2 min read
How to work with document.embeds in JavaScript ?
The document. embeds is a property in JavaScript that provides access to all embedded elements such as <embed> and <object> tags within the current document. These embedded elements are typically used to display external content, such as media files (e.g., videos, audio) or interactive c
3 min read
How to remove an HTML element using JavaScript ?
Removing an HTML element using JavaScript involves deleting it from the DOM, typically using methods like element.remove() or parentNode.removeChild(). This approach updates the webpage dynamically, allowing for responsive interactions by removing unwanted or outdated elements based on user actions
3 min read
How to get HTML content of an iFrame using JavaScript ?
The <iframe> tag specifies an inline frame. It allows us to load a separate HTML file into an existing document. Code snippet:function getIframeContent(frameId) { let frameObj = document.getElementById(frameId); let frameContent = frameObj. contentWindow.document.body.innerHTML; alert("frame c
1 min read
How to work with document.documentElement in JavaScript?
In JavaScript, document.documentElement is a fundamental property that refers to the root element of an HTML document. This property provides a way to access and manipulate the entire HTML document structure. In this tutorial, we will focus on how to work with document.documentElement in JavaScript.
2 min read
How to Display Images in JavaScript ?
To display images in JavaScript, we have different approaches. In this article, we are going to learn how to display images in JavaScript. Below are the approaches to display images in JavaScript: Table of Content Using CreateElementUsing InnerHTMLApproach 1: Using CreateElementIn an HTML document,
2 min read
How to Get the Entire HTML Document as a String Using JavaScript?
We will explore how to retrieve the entire HTML document as a string using JavaScript. This can be useful when you want to inspect or manipulate the entire structure of a webpage. Methods to Get the Entire HTML Document as a StringThere are two primary methods for extracting the HTML content of a pa
2 min read
How to call JavaScript function in HTML ?
In HTML, you can easily call JavaScript functions using event attributes like onclick and onload. Just reference the function name within these attributes to trigger it. You can also call functions directly within script blocks using standard JavaScript syntax. Let's create an HTML structure with so
2 min read
Word Guessing Game using HTML CSS and JavaScript
In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
4 min read