Skip to main content

Wordinserter

Build Status image1 image2 image3 image4

This module allows you to insert HTML into a Word Document, as well as allowing you to programmatically build word documents in pure Python (Python 3.x only at the moment). After running pip install wordinserter you can use the wordinserter CLI to quickly generate test documents:

# Download https://raw.githubusercontent.com/orf/wordinserter/master/tests/docs/table_widths.html
wordinserter table_widths.html --style="table { background-color: red }"

This should open Word and insert three tables, each of them styled with a red background.

The library is stable and has been used to generate tens of thousands of reports, and currently supports many features (all controlled through HTML):

  • Common tags, including tables, lists, code blocks, images, hyperlinks, footnotes, headers, paragraphs, styles (b i em)

  • Named bookmarks in documents via element id attributes

  • A subset of CSS for elements, with more that can be easily added as needed

  • Including document-wide stylesheets while adding elements

  • In-built syntax highlighting for <pre> and <code> blocks

  • Supports complex merged tables, with rowspans and colspans

  • Arbitrarily nested lists of differing types (bullet, numbered, roman numerals)

  • Hyperlinks to bookmarks within the document using classic links or using Word ‘fields’

  • Images, with support for footnotes, 404 and embedded base64 data-uri images

  • Basic whitespace handling

There is a comparison document showing the output of WordInserter against Chrome, check it out to see what the library can do.

API

The API is really simple to use:

from wordinserter import parse, insert

operations = parse(html, parser="html")
insert(operations, document=document, constants=constants)

Inserting HTML into a Word document is a two step process: first the input has to be parsed into a sequence of operations, which is then inserted into a Word document. This library currently only supports inserting using the Word COM interface which means it is Windows specific at the moment.

Below is a more complex example including starting word that will insert a representation of the HTML code into the new word document, including the image, caption and list.

from wordinserter import insert, parse
from comtypes.client import CreateObject

# This opens Microsoft Word and creates a new document.
word = CreateObject("Word.Application")
word.Visible = True # Don't set this to True in production!
document = word.Documents.Add()
from comtypes.gen import Word as constants

html = """
<h3>This is a title</h3>
<p><img src="http://placehold.it/150x150" alt="I go below the image as a caption"></p>
<p><i>This is <b>some</b> text</i> in a <a href="http://google.com">paragraph</a></p>
<ul>
    <li>Boo! I am a <b>list</b></li>
</ul>
"""

# Parse the HTML into a list of operations then feed them into insert.
operations = parse(html, parser="html")
insert(operations, document=document, constants=constants)

What’s with the constants part? Wordinserter is agnostic to the COM library you use. Each library exposes constant values that are needed by Wordinserter in a different way: the pywin32 library exposes it as win32com.client.constants whereas the comtypes library exposes them as a module that resides in comtypes.gen. Rather than guess which one you are using Wordinserter requires you to pass the right one in explicitly. If you need to mix different constant groups you can use the CombinedConstants class:

from wordinserter.utils import CombinedConstants
from comtypes.gen import Word as word_constants
from comtypes.gen import Office as office_constants

constants = CombinedConstants(word_constants, office_constants)

Install

Get it from PyPi here, using pip install wordinserter. This has been built with word 2010 and 2013, older versions may produce different results.

Supported Operations

WordInserter currently supports a range of different operations, including code blocks, font size/colors, images, hyperlinks, numbered and bullet lists, table borders and padding.

Stylesheets?

Wordinserter has support for stylesheets! Every element can be styled with inline styles (style='whatever') but this gets tedious at scale. You can pass CSS stylesheets to the parse function:

html = "<p class="mystyle">Hello Word</p>"
stylesheet = """
.mystyle {
    color: red;
}
"""

operations = parse(html, parser="html", stylesheets=[stylesheet])
insert(operations, document=document, constants=constants)

This will render “Hello Word” in red. Inheritance is respected, so child styles override parent ones.

Why aren’t my lists showing up properly?

There are two ways people write lists in HTML, one with each sub-list as a child of the parent list, or as a child of a list element. Below is a sample of the two different ways, both of which display correctly in all browsers:

<ol>
    <li>
        I'm a list element
    </li>
    <ul>
        <li>I'm a sub list!</li>
    </ul>
</ol>
<ol>
    <li>
        I'm a list element
        <ul>
            <li>I'm a sub list!</li>
        </ul>
    </li>
</ol>

The second way is correct according to the HTML specification. lxml parses the first structure incorrectly in some cases, which leads to weird list behavior. There isn’t much this library can do about that, so make sure your lists are in the second format.

One other thing to note: Word does not support lists with mixed list-types on a single level. i.e this HTML will render incorrectly:

<ol>
    <li>
        <ul><li>Unordered List On Level #1</li></ul>
        <ol><li>Ordered List On Level #1</li></ul>
    </li>
</ol>

Release files for wordinserter 1.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wordinserter 1.1.3
File Size Uploaded
wordinserter-1.1.3.tar.gz 41.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for wordinserter 1.1.3
File Interpreter ABI Platform
wordinserter-1.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 84.5 kB

Release files / wordinserter-1.1.3.tar.gz

Download URL wordinserter-1.1.3.tar.gz
Size 41.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a51316c532df1b43a30d939bb18c4d8551cdefcbc03c574225273b3be06ee91e
BLAKE2b-256 checksum
How to use checksums
c61d2dc1f86e411d1236e6fdde2b6c884c058cf06645083231381364bb42588c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.7.3 requests-toolbelt/0.9.1 tqdm/4.28.1 CPython/3.7.2

Release files / wordinserter-1.1.3-py3-none-any.whl

Download URL wordinserter-1.1.3-py3-none-any.whl
Size 42.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
80db754f8343620745205dfe3a0bb1acbfd0e7e1f0e84ed7c9d58627f3d4143a
BLAKE2b-256 checksum
How to use checksums
42e8cfede79814a1b8699943504d80a90131d62007a187e60fb035db0538c4a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.7.3 requests-toolbelt/0.9.1 tqdm/4.28.1 CPython/3.7.2

Release history Release notifications | RSS feed

This release

1.1.3 This release

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

0.9.6

2 release files

0.9.5

2 release files

0.9.4.4

1 release file

0.9.4.3

1 release file

0.9.4.2

1 release file

0.9.4.1

1 release file

0.9.4

1 release file

0.9.3

1 release file

0.9.2.6

1 release file

0.9.2.5

1 release file

0.9.2.4

1 release file

0.9.2.2

1 release file

0.9.2.1

1 release file

0.9.2

0.9.1

1 release file

0.9

1 release file

0.8.8

1 release file

0.8.7

1 release file

0.8.6

1 release file

0.8.5

1 release file

0.8.4

1 release file

0.8.3

1 release file

0.8.2

1 release file

0.8.1

1 release file

0.8

1 release file

0.7.9

1 release file

0.7.8

1 release file

0.7.7.1

1 release file

0.7.7

1 release file

0.7.6

1 release file

0.7.5

1 release file

0.7.4

1 release file

0.7.3

1 release file

0.7.2

1 release file

0.7.1

1 release file

0.7

1 release file

0.6.13

1 release file

0.6.12

1 release file

0.6.11

1 release file

0.6.10

1 release file

0.6.9.1

1 release file

0.6.9

1 release file

0.6.7

1 release file

0.6.6

1 release file

0.6.5

1 release file

0.6.2

1 release file

0.6.1

1 release file

0.6

1 release file

0.5.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page