October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
document preview

How to Preview DOCX Files in JavaScript

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a JavaScript web app, choose Mammoth.js when you want DOCX content converted into semantic HTML, or a browser renderer such as docx-preview when you want a read-only display that looks more like a document. Neither approach guarantees a pixel-perfect match to Microsoft Word. If the document must be manipulated inside Word or another supported Office host, use Office.js instead of treating it as a standalone DOCX viewer.

Choose the preview approach that matches the job

Need Approach Main trade-off
Document content that fits naturally into a web page Mammoth.js Produces semantic HTML, not a visual copy of Word formatting; complex files may not convert perfectly.
A read-only, document-like browser display docx-preview Renders common content in the browser but has pagination and field limitations; it does not promise pixel-perfect Word output.
An add-in running inside Word or another supported Office application Office.js Works in an Office-host context, and API support varies by application, version, and platform.

There is no universal best choice: DOCX stores document structure and layout semantics that do not map perfectly to HTML and CSS. Decide whether your users need readable content or a page-like presentation, then test files representative of what they will upload.

Preview a DOCX as semantic HTML with Mammoth.js

Mammoth converts Word document structure into HTML. For example, a Word paragraph styled as “Heading 1” maps to an HTML heading rather than being styled to exactly reproduce its original font, color, and size. This is useful when the preview should inherit your application’s typography and layout.

The browser-side flow is: read a selected file as bytes, pass those bytes to Mammoth’s convertToHtml, inspect its returned HTML and conversion messages, then render the result only after applying your application’s security policy. The project’s documentation describes an API that returns both an HTML value and conversion messages. Its maintainers also caution that complex documents may not convert perfectly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
The Microsoft Office 365 Bible: The Most Updated and Complete Guide to Excel, Word, PowerPoint, Outlook, OneNote, OneDrive, Teams, Access, and Publisher from Beginners to Advanced
  • The Microsoft Office 365 Bible: The Most Updated and Complete Guide to Excel, Word, PowerPoint, Outlook, OneNote, OneDrive, Teams, Access, and Publisher from Beginners to Advanced
  • ABIS BOOK
// Browser-side flow; make the Mammoth browser build available to this module
// according to the installation method used by your application.
const fileInput = document.querySelector('#docx-file');
const preview = document.querySelector('#preview');
const status = document.querySelector('#status');

fileInput.addEventListener('change', async () => {
  const file = fileInput.files?.[0];
  if (!file) return;

  if (!file.name.toLowerCase().endsWith('.docx')) {
    status.textContent = 'Choose a .docx file.';
    return;
  }

  try {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.convertToHtml({ arrayBuffer });

    // Do not insert unsanitized conversion output from an untrusted file.
    // Apply your chosen HTML sanitizer and content policy here.
    preview.innerHTML = sanitizeHtml(result.value);
    status.textContent = result.messages.length
      ? `${result.messages.length} conversion message(s); check the console.`
      : 'Preview ready.';
    console.info('Mammoth conversion messages:', result.messages);
  } catch (error) {
    status.textContent = 'The document could not be converted.';
    console.error(error);
  }
});

This example deliberately leaves sanitizeHtml as an application-provided function: choose and configure a sanitizer appropriate to your product rather than assuming Mammoth makes the result safe. Mammoth explicitly does not sanitize input. Do not replace the call with raw result.value in innerHTML for uploaded or otherwise untrusted documents.

What Mammoth can and cannot preserve

Mammoth supports document features including headings, lists, configurable style mappings, tables, notes, images, text formatting, links, line breaks, text boxes, and comments. Its aim is semantic conversion; appearance details and complicated layout may be lost or transformed. Use conversion messages to identify issues the library reports, and check the resulting document against your product’s requirements.

Render a more document-like view with docx-preview

Use a browser renderer when users need a read-only display that retains more of the document’s page-oriented character than semantic HTML. The office-kit wrapper documents previewToDOM, which accepts a parsed Docx value or raw Uint8Array, Blob, or ArrayBuffer data and renders into a DOM element. It returns a handle with a dispose() method.

// `docxPreview` represents the renderer API made available by your chosen
// docx-preview integration. The office-kit wrapper documents previewToDOM.
const file = fileInput.files?.[0];
if (file) {
  const arrayBuffer = await file.arrayBuffer();
  const renderHandle = await docxPreview.previewToDOM(arrayBuffer, preview);

  // When replacing the document or removing the preview component:
  renderHandle.dispose();
}

Confirm the exact import and call signature for the package or wrapper version you install; this example shows the documented input and lifecycle shape, not a package-manager setup. The wrapper describes support for body text and paragraph styling, lists, tables, inline images, hyperlinks, headers, footers, and notes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Expectations for pagination and fields

  • There is no live repagination: the preview does not continuously recalculate page breaks as a word processor does.
  • Page breaks follow breaks declared in the source document.
  • Fields such as a table of contents or page number can show cached display values when present; otherwise field instructions may appear.
  • Tab-stop and list edge cases are documented limitations.
  • The renderer is read-only, and its wrapper states that pixel-perfect Word rendering is out of scope because HTML and CSS cannot reproduce every WordprocessingML page semantic.

These limitations matter if users treat the preview as an authoritative print layout. If the application only needs a convenient browser reading view, a page-like rendering may still be appropriate; if exact print output is critical, do not promise that this browser preview reproduces Word.

Use Office.js only when the document is in an Office host

Office.js lets an Office add-in interact with the content of the Office document in which that add-in runs. It is relevant when your product is an add-in embedded in Word or another supported host, not the default way to show an arbitrary uploaded DOCX in a standalone web app. Microsoft loads the API library from its CDN, and support varies across Office applications, versions, and platforms.

Microsoft’s Word preview API documentation says those preview APIs are subject to change and are not intended for production or business-critical documents. Treat them as development-only unless the current Microsoft documentation says otherwise; do not build a production viewer on a preview API without verifying its status.

Make the preview safe and dependable

Handle untrusted files as untrusted input

A DOCX uploaded by a user is not trustworthy merely because it is a document file, and converted HTML is not safe merely because a library produced it. Mammoth says it does no sanitization. Apply an appropriate sanitizer and content policy before inserting generated markup into the page. Also avoid displaying active content or remote resources contrary to your application’s security requirements.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the document features your users actually rely on

Build a small fixture set that exercises tables, images, page breaks, headers, footers, and fields. Compare the result with the expected behavior for your chosen preview style. This is a practical validation method, not a claim that either library has a particular compatibility percentage. Include complex files likely to expose the trade-off between semantic conversion and page-oriented rendering.

Keep lifecycle and failure states visible

  • Show a loading state while a file is read and converted or rendered.
  • Handle unsupported files, empty selections, conversion errors, and malformed documents with a clear user-facing message.
  • For a document-like renderer, dispose of the prior render handle when replacing a preview or unmounting its container.
  • For Mammoth, inspect conversion messages rather than silently assuming every feature mapped as intended.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common preview problems

Symptom Likely explanation What to do
Formatting differs from Word Mammoth prioritizes semantic HTML; browser renderers cannot reproduce every Word layout rule. Use Mammoth for structure, docx-preview for a more document-like view, and set expectations about fidelity.
Some content is missing or transformed The file uses complex structures or formatting that do not map cleanly to HTML. Check Mammoth conversion messages, test the affected feature in both approaches, and communicate any known unsupported behavior.
Page numbers or table of contents look stale Fields may display cached values; field evaluation is not performed like Word. Do not treat those values as dynamically recalculated. Verify the document in an appropriate Office application if current field values matter.
Page breaks do not move after content changes docx-preview documents no live repagination. Use it as a read-only preview rather than an editable word processor, or select a workflow that produces the required final layout.
Unexpected HTML behavior after conversion The application inserted converted content without sanitizing it. Sanitize output from untrusted DOCX files before insertion and apply your site’s content policy.
The Office API is unavailable on a user’s setup Office.js support differs by host application, version, and platform. Check Microsoft’s current support documentation for the exact target host and avoid assuming standalone-browser availability.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not a DOCX conversion or rendering library, so it cannot turn an uploaded DOCX into a browser preview. It can capture a web page that your app has already rendered. For example, after you deploy a page containing the preview:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Before a website capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides screenshot and PDF tools for AI agents, and its plans include 1,000 screenshots a month free without a card; paid plans start at $5 for 3,000. Those features concern page capture, not DOCX parsing.

Sign up for ScreenshotNeo’s free 1,000 screenshots a month, with no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What to choose

For semantic document content in your app, start with Mammoth and treat its output as untrusted HTML until sanitized. For a read-only view that should feel more like a document, evaluate docx-preview against representative files and account for its pagination and field limitations. Use Office.js when the document interaction belongs inside an Office add-in. In every case, test the actual document features your users need and describe the fidelity your preview does—and does not—provide.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.