Open In App

How to Display Word Document in HTML using JavaScript?

Last Updated : 18 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article

Similar Reads