docx vs html-docx-js vs html-to-docx
Generating Word Documents in Node.js and Browser
docxhtml-docx-jshtml-to-docxSimilar Packages:

Generating Word Documents in Node.js and Browser

docx, html-docx-js, and html-to-docx are JavaScript libraries used to create Microsoft Word (.docx) files. docx is a programmatic builder that lets you construct documents element-by-element using JavaScript objects. html-docx-js and html-to-docx focus on converting existing HTML content into Word format. While docx offers fine-grained control over layout and styling, the HTML converters prioritize speed and ease of use when migrating web content to documents.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
docx05,7754.65 MB1509 days agoMIT
html-docx-js01,149-8310 years agoMIT
html-to-docx04834.8 MB1063 years agoMIT

Generating Word Documents: docx vs html-docx-js vs html-to-docx

Creating Word documents in JavaScript is a common requirement for reporting, exporting data, or archiving web content. The three main contenders — docx, html-docx-js, and html-to-docx — take very different approaches. docx builds files from scratch using code, while the other two convert HTML strings into documents. Let's look at how they handle real-world engineering tasks.

🏗️ Document Creation: Programmatic vs HTML Conversion

docx requires you to define every part of the document using JavaScript objects.

  • You create paragraphs, tables, and images explicitly.
  • This gives you full control but requires more code.
// docx: Programmatic creation
const { Document, Packer, Paragraph, TextRun } = require("docx");

const doc = new Document({
  sections: [{
    properties: {},
    children: [
      new Paragraph({
        children: [new TextRun("Hello World")],
      }),
    ],
  }],
});

Packer.toBuffer(doc).then((buffer) => {
  // Save buffer to file
});

html-docx-js takes an HTML string and converts it directly.

  • You write standard HTML and CSS.
  • The library wraps it in a Word-compatible format.
// html-docx-js: HTML conversion
const htmlDocx = require("html-docx-js");

const htmlContent = `<!DOCTYPE html><html><body><h1>Hello World</h1></body></html>`;

const converted = htmlDocx.asBlob(htmlContent);
// Returns a Blob object ready for download or saving

html-to-docx also converts HTML but supports more modern options.

  • It allows configuration for page size and margins.
  • Better handling of complex HTML structures than html-docx-js.
// html-to-docx: HTML conversion with options
const HTMLtoDOCX = require("html-to-docx");

const htmlContent = `<h1>Hello World</h1>`;

HTMLtoDOCX(htmlContent, null, {
  table: { row: { cantSplit: true } },
  footer: true,
}).then((fileBuffer) => {
  // Save buffer to file
});

🎨 Styling and Layout Control

docx uses its own styling system that maps to Word's internal XML.

  • You define styles in a styles array and reference them by ID.
  • Ensures consistent rendering across different Word versions.
// docx: Custom styles
const doc = new Document({
  styles: {
    paragraphStyles: [{
      id: "heading1",
      name: "Heading 1",
      basedOn: "Normal",
      quickFormat: true,
      run: { size: 28, bold: true },
    }],
  },
  sections: [{
    children: [
      new Paragraph({
        text: "Title",
        heading: "Heading1",
      }),
    ],
  }],
});

html-docx-js relies on inline CSS or style tags.

  • Support is limited to basic CSS properties.
  • Complex layouts like flexbox or grid often break.
// html-docx-js: Inline CSS
const html = `<h1 style="color: blue; font-size: 24pt;">Title</h1>`;
const converted = htmlDocx.asBlob(html);
// Advanced CSS may be ignored or rendered incorrectly

html-to-docx supports a wider range of CSS properties.

  • It attempts to map CSS to WordML styles automatically.
  • Still struggles with complex positioning but handles text styling well.
// html-to-docx: CSS mapping
const html = `<h1 style="color: blue; font-size: 24pt;">Title</h1>`;
HTMLtoDOCX(html).then((buffer) => {
  // Better CSS fidelity than html-docx-js
});

🖼️ Image Handling

docx requires images to be added as media elements with explicit dimensions.

  • You must provide the image buffer or URL and set width/height.
  • Very reliable for reports with logos or charts.
// docx: Image insertion
const doc = new Document({
  sections: [{
    children: [
      new Paragraph({
        children: [
          new ImageRun({
            data: fs.readFileSync("image.png"),
            transformation: { width: 100, height: 100 },
          }),
        ],
      }),
    ],
  }],
});

html-docx-js supports images via standard <img> tags.

  • Requires base64 encoded data URIs for best results.
  • External URLs may fail depending on the environment.
// html-docx-js: Image tag
const html = `<img src="data:image/png;base64,..." width="100" />`;
const converted = htmlDocx.asBlob(html);
// External URLs often blocked by security policies

html-to-docx also uses <img> tags but handles fetching better.

  • Can fetch external images if configured correctly.
  • More robust handling of image scaling within the document.
// html-to-docx: Image fetching
const html = `<img src="https://example.com/image.png" />`;
HTMLtoDOCX(html, null, {
  converter: {
    image: { url: "https://example.com/image.png" }
  }
}).then((buffer) => {
  // Handles external resources more gracefully
});

🛠️ Maintenance and Ecosystem

docx is actively maintained with frequent updates.

  • Has a large community and extensive documentation.
  • Regularly adds support for new Word features.
// docx: Active development
// npm install docx
// Regularly updated with new features like content controls

html-docx-js is largely stagnant with minimal updates.

  • Many open issues regarding CSS support and bugs.
  • Risk of security vulnerabilities due to lack of patches.
// html-docx-js: Legacy status
// npm install html-docx-js
// Last major updates were years ago; use with caution

html-to-docx is actively maintained as a modern alternative.

  • Fixes bugs found in html-docx-js.
  • Better suited for production environments requiring HTML conversion.
// html-to-docx: Modern alternative
// npm install html-to-docx
// Actively maintained with better CSS support

🌐 Environment Support

docx works in both Node.js and browsers.

  • Uses standard web APIs for file saving in the browser.
  • No polyfills needed for most modern environments.
// docx: Browser support
Packer.toBlob(doc).then((blob) => {
  saveAs(blob, "document.docx"); // Using file-saver or similar
});

html-docx-js was originally built for browsers but works in Node.

  • Relies on Blob objects which may need polyfills in older Node versions.
  • Less optimized for server-side generation.
// html-docx-js: Environment
const converted = htmlDocx.asBlob(html);
// May require buffer conversion in Node.js environments

html-to-docx is designed with Node.js in mind but supports browsers.

  • Returns buffers by default, easy to save on server.
  • Can be adapted for client-side use with minor changes.
// html-to-docx: Node.js focus
HTMLtoDOCX(html).then((buffer) => {
  fs.writeFileSync("document.docx", buffer);
});

📊 Summary: Key Differences

Featuredocxhtml-docx-jshtml-to-docx
ApproachProgrammatic BuilderHTML ConverterHTML Converter
ControlHigh (Pixel-perfect)Low (HTML dependent)Medium (CSS mapped)
Maintenance✅ Active❌ Legacy/Stagnant✅ Active
Learning CurveSteep (API heavy)Low (HTML knowledge)Low (HTML knowledge)
Best ForReports, InvoicesQuick HTML exportsRich HTML content

💡 The Big Picture

docx is the professional choice for generating structured documents.

  • If you are building an invoice generator, a contract system, or a report engine, this is the only serious option.
  • It requires more code but guarantees the document looks exactly how you intend.

html-docx-js should be avoided in new projects.

  • It is effectively deprecated in favor of better alternatives.
  • Using it introduces technical debt and potential rendering bugs.

html-to-docx is the right tool for content export.

  • If your users write content in a rich text editor and want to download it as Word, use this.
  • It balances ease of use with reasonable fidelity to the original HTML.

Final Thought: Don't try to force HTML converters to do programmatic layout work. If you need tables, headers, and footers to align perfectly, invest the time in docx. If you just need to save a blog post, html-to-docx will save you days of development time.

How to Choose: docx vs html-docx-js vs html-to-docx

  • docx:

    Choose docx if you need precise control over the document structure, such as custom headers, footers, tables, or complex styling. It is the best choice for generating reports, invoices, or templates where consistency and layout matter more than quick HTML conversion. It is actively maintained and works in both Node.js and browsers.

  • html-docx-js:

    Avoid html-docx-js for new projects. It is largely considered legacy software with limited maintenance and known issues with modern CSS support. Only use it if you are maintaining an older codebase that already depends on it and migration is not feasible.

  • html-to-docx:

    Choose html-to-docx if your primary goal is to convert rich HTML content (like blog posts or emails) into Word documents quickly. It handles CSS styling better than html-docx-js and is more actively maintained. It is ideal when you already have HTML content and do not need to build the document structure manually.

README for docx

clippy the assistant

Easily generate and modify .docx files with JS/TS. Works for Node and on the Browser.


NPM version Downloads per month GitHub Action Workflow Status Known Vulnerabilities PRs Welcome codecov Docx.js Editor

drawing

Demo

Browser

Here are examples of docx being used with basic HTML/JS in a browser environment:

Here are examples of docx working in Angular:

Here are examples of docx working in React:

Here is an example of docx working in Vue.js:

Node

Press endpoint on the RunKit website:

RunKit Instructions

More here

How to use & Documentation

Please refer to the documentation at https://docx.js.org/ for details on how to use this library, examples and much more!

Playground

Experience docx in action through Docx.js Editor, an interactive playground where you can code and preview the results in real-time.

Examples

Check the demo folder for examples.

Contributing

Read the contribution guidelines here.

Used by

drawing drawing drawing drawing drawing drawing drawing drawing drawing drawing drawing drawing drawing drawing drawing

...and many more!


patreon browserstack

Made with 💖