Skip to main content

How to preview a word document in HTML using javascript

You can preview a word document in HTML page using javascript. You can display word documents (.doc, .docx) as HTML document in the browser on choose file.

  • Preview MS word docx document on choose file using mammoth

    Javascript CDN (jQuery and mammoth library)

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.18/mammoth.browser.min.js" integrity="sha512-Z8jpnlnXO9rena5GNKiX0EHQRNLLh0LobtlTESOc55UMcQPOdxBpSMrU9MMZI1b5Xoph9bPMFbNyi9s33Du0EA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    HTML 

    Input file to choose file and target div to preview docx content

    <input type="file" id="file" name="document" accept=".doc, .docx"/>
    <div id="docPreview"></div>

    Javascript code

    <script>
        $("body").on("change", "#file", function(e){
            parseWordDocxFile(e.target.files, '#docPreview');
        });
    
        function parseWordDocxFile(inputElement, showDiv) {
            var files = inputElement || [];
            if (!files.length) return;
            var file = files[0];
            console.time();
            var reader = new FileReader();
            reader.onloadend = function(event) {
                
                var arrayBuffer = reader.result;
                mammoth.convertToHtml({arrayBuffer: arrayBuffer}).then(function (resultObject) {
                    console.log(resultObject.value);
                    $(showDiv).html(resultObject.value);
                    console.log(resultObject.value);
                })
                console.timeEnd();
                mammoth.extractRawText({arrayBuffer: arrayBuffer}).then(function (resultObject) {
                    result2.innerHTML = resultObject.value;
                    console.log(resultObject.value);
                })
    
                mammoth.convertToMarkdown({arrayBuffer: arrayBuffer}).then(function (resultObject) {
                    result3.innerHTML = resultObject.value;
                    console.log(resultObject.value);
                })
            };
            reader.readAsArrayBuffer(file);
        }
    </script>

    Here we have a mammoth ajax library to display the document on the chosen file. Here we have two html element input file to choose the file and target div to show the output (doc content) on choosing the input file.

  • Back to code snippet queries related javascript