html-docx-js

repository·master·Indexed 22 days ago

https://github.com/evidenceprime/html-docx-js

A lightweight library for converting HTML documents to DOCX format (Microsoft Word 2007+) in the browser or Node.js. It uses the 'altchunks' feature to embed content and supports base64 DATA URIs for images. The asBlob method allows for the configuration of page orientation and margins.

Tokens
649
Snippets
2
Records
5
Agent score
28%

What's inside html-docx-js

  1. How html-docx-js handles images

    master

    The library only supports images that are inlined as base64 DATA URIs.

    If your HTML contains regular image sources (e.g., <img src="/path/to/image.png">), you must convert them to base64 strings on the fly before passing the HTML to asBlob. A reference implementation for this conversion can be found in the convertImagesToBase64 function within the project's test samples.

  2. Convert HTML to DOCX using asBlob

    master

    To generate a DOCX file, pass a complete, valid HTML string (including DOCTYPE, <html>, and <body> tags) to the asBlob method. This method returns a Blob (in the browser) or a Buffer (in Node.js) containing the output file.

    Note: Including the full HTML structure allows you to include CSS rules within <style> tags.

    var converted = htmlDocx.asBlob(content);
    saveAs(converted, 'test.docx');
  3. Configure page orientation and margins in asBlob

    master

    The asBlob method accepts an optional configuration object to control the document's page setup.

    Options

    • orientation: 'landscape' or 'portrait' (default).
    • margins: A map of margin sizes expressed in twentieths of a point.
      • top: number (default: 1440, which is 2.54 cm)
      • right: number (default: 1440)
      • bottom: number (default: 1440)
      • left: number (default: 1440)
      • header: number (default: 720)
      • footer: number (default: 720)
      • gutter: number (default: 0)

    Example usage:

    var converted = htmlDocx.asBlob(content, {
      orientation: 'landscape',
      margins: {
        top: 720
      }
    });
    saveAs(converted, 'test.docx');
  4. Compatibility and Limitations

    master

    Supported Environments

    • Browsers: Any modern browser supporting Blobs (tested on Chrome 36, Safari 7, and IE 10). For older browsers, use Blob.js.
    • Node.js: Supported using Buffer instead of Blob (tested on v0.10.12).

    Limitations

    • Microsoft Word for Mac 2008: Does not support the 'altchunks' feature used by this library.
    • Other Viewers: Not supported by LibreOffice or Google Docs.
    • Safari: Saving files in Safari is unreliable; a Flash-based approach like Downloadify may be required for reliable downloads.