Package: mammoth
Mammoth is designed to convert .docx documents, such as those created by
Microsoft Word, Google Docs and LibreOffice, and convert them to HTML.
Mammoth aims to produce simple and clean HTML by using semantic
information in the document, and ignoring other details. For instance,
Mammoth converts any paragraph with the styleHeading 1toh1elements, rather than attempting to exactly copy the styling (font, text
size, colour, etc.) of the heading.There’s a large mismatch between the structure used by .docx and the
structure of HTML, meaning that the conversion is unlikely to be perfect
for more complicated documents. Mammoth works best if you only use
styles to semantically mark up your document.The following features are currently supported:Headings.Lists.Customisable mapping from your own docx styles to HTML. For instance,
you could convertWarningHeadingtoh1.warningby providing
an appropriate style mapping.Tables. The formatting of the table itself, such as borders, is
currently ignored, but the formatting of the text is treated the same
as in the rest of the document.Footnotes and endnotes.Images.Bold, italics, underlines, strikethrough, superscript and subscript.Links.Line breaks.Text boxes. The contents of the text box are treated as a separate
paragraph that appears after the paragraph containing the text box.Comments.Installationpip install mammothOther supported platformsJavaScript, both the
browser and node.js. Availableon
npm.WordPress.Java/JVM. Availableon Maven
Central..NET. Availableon NuGet.UsageCLIYou can convert docx files by passing the path to the docx file and the
output file. For instance:mammoth document.docx output.htmlIf no output file is specified, output is written to stdout instead.The output is an HTML fragment, rather than a full HTML document,
encoded with UTF-8. Since the encoding is not explicitly set in the
fragment, opening the output file in a web browser may cause Unicode
characters to be rendered incorrectly if the browser doesn’t default to
UTF-8.ImagesBy default, images are included inline in the output HTML. If an output
directory is specified by--output-dir, the images are written to
separate files instead. For instance:mammoth document.docx --output-dir=output-dirExisting files will be overwritten if present.StylesA custom style map can be read from a file using--style-map. For
instance:mammoth document.docx output.html --style-map=custom-style-mapWherecustom-style-maplooks something like:p[style-name='Aside Heading'] => div.aside > h2:fresh
p[style-name='Aside Text'] => div.aside > p:freshA description of the syntax for style maps can be found in the section“Writing style maps”.MarkdownMarkdown support is deprecated. Generating HTML and using a separate
library to convert the HTML to Markdown is recommended, and is likely to
produce better results.Using--output-format=markdownwill cause Markdown to be generated.
For instance:mammoth document.docx --output-format=markdownLibraryBasic conversionTo convert an existing .docx file to HTML, pass a file-like object tomammoth.convert_to_html. The file should be opened in binary mode.
For instance:importmammothwithopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file)html=result.value# The generated HTMLmessages=result.messages# Any messages, such as warnings during conversionYou can also extract the raw text of the document by usingmammoth.extract_raw_text. This will ignore all formatting in the
document. Each paragraph is followed by two newlines.withopen("document.docx","rb")asdocx_file:result=mammoth.extract_raw_text(docx_file)text=result.value# The raw textmessages=result.messages# Any messagesCustom style mapBy default, Mammoth maps some common .docx styles to HTML elements. For
instance, a paragraph with the style nameHeading 1is converted to
ah1element. You can pass in a custom map for styles by passing an
options object with astyle_mapproperty as a second argument toconvert_to_html. A description of the syntax for style maps can be
found in the section“Writing style maps”. For
instance, if paragraphs with the style nameSection Titleshould be
converted toh1elements, and paragraphs with the style nameSubsection Titleshould be converted toh2elements:importmammothstyle_map="""
p[style-name='Section Title'] => h1:fresh
p[style-name='Subsection Title'] => h2:fresh
"""withopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file,style_map=style_map)User-defined style mappings are used in preference to the default style
mappings. To stop using the default style mappings altogether, passinclude_default_style_map=False:result=mammoth.convert_to_html(docx_file,style_map=style_map,include_default_style_map=False)Custom image handlersBy default, images are converted to<img>elements with the source
included inline in thesrcattribute. This behaviour can be changed
by setting theconvert_imageargument to animage
converter.For instance, the following would replicate the default behaviour:defconvert_image(image):withimage.open()asimage_bytes:encoded_src=base64.b64encode(image_bytes.read()).decode("ascii")return{"src":"data:{0};base64,{1}".format(image.content_type,encoded_src)}mammoth.convert_to_html(docx_file,convert_image=mammoth.images.img_element(convert_image))BoldBy default, bold text is wrapped in<strong>tags. This behaviour
can be changed by adding a style mapping forb. For instance, to
wrap bold text in<em>tags:style_map="b => em"withopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file,style_map=style_map)ItalicBy default, italic text is wrapped in<em>tags. This behaviour can
be changed by adding a style mapping fori. For instance, to wrap
italic text in<strong>tags:style_map="i => strong"withopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file,style_map=style_map)UnderlineBy default, the underlining of any text is ignored since underlining can
be confused with links in HTML documents. This behaviour can be changed
by adding a style mapping foru. For instance, suppose that a source
document uses underlining for emphasis. The following will wrap any
explicitly underlined source text in<em>tags:importmammothstyle_map="u => em"withopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file,style_map=style_map)StrikethroughBy default, strikethrough text is wrapped in
tags. This
behaviour can be changed by adding a style mapping forstrike. For
instance, to wrap strikethrough text in<del>tags:style_map="strike => del"withopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file,style_map=style_map)CommentsBy default, comments are ignored. To include comments in the generated
HTML, add a style mapping forcomment-reference. For instance:style_map="comment-reference => sup"withopen("document.docx","rb")asdocx_file:result=mammoth.convert_to_html(docx_file,style_map=style_map)Comments will be appended to the end of the document, with links to the
comments wrapped using the specified style mapping.APImammoth.convert_to_html(fileobj, **kwargs)Converts the source document to HTML.fileobj: a file-like object containing the source document. Files
should be opened in binary mode.style_map: a string to specify the mapping of Word styles to
HTML. See the section“Writing style maps”for a description of the syntax.include_embedded_style_map: by default, if the document contains
an embedded style map, then it is combined with the default style
map. To ignore any embedded style maps, passinclude_embedded_style_map=False.include_default_style_map: by default, the style map passed instyle_mapis combined with the default style map. To stop using
the default style map altogether, passinclude_default_style_map=False.convert_image: by default, images are converted to<img>elements with the source included inline in thesrcattribute.
Set this argument to animage converterto
override the default behaviour.ignore_empty_paragraphs: by default, empty paragraphs are
ignored. Set this option toFalseto preserve empty paragraphs in
the output.id_prefix: a string to prepend to any generated IDs, such as
those used by bookmarks, footnotes and endnotes. Defaults to an empty
string.transform_document: if set, this function is applied to the
document read from the docx file before the conversion to HTML. The
API for document transforms should be considered unstable. Seedocument transforms.Returns a result with the following properties:value: the generated HTMLmessages: any messages, such as errors and warnings, generated
during the conversionmammoth.convert_to_markdown(fileobj, **kwargs)Markdown support is deprecated. Generating HTML and using a separate
library to convert the HTML to Markdown is recommended, and is likely to
produce better results.Converts the source document to Markdown. This behaves the same asconvert_to_html, except that thevalueproperty of the result
contains Markdown rather than HTML.mammoth.extract_raw_text(fileobj)Extract the raw text of the document. This will ignore all formatting in
the document. Each paragraph is followed by two newlines.fileobj: a file-like object containing the source document. Files
should be opened in binary mode.Returns a result with the following properties:value: the raw textmessages: any messages, such as errors and warningsmammoth.embed_style_map(fileobj, style_map)Embeds the style mapstyle_mapintofileobj. When Mammoth reads
a file object, it will use the embedded style map.fileobj: a file-like object containing the source document. Files
should be opened for reading and writing in binary mode.style_map: the style map to embed.ReturnsNone.MessagesEach message has the following properties:type: a string representing the type of the message, such as"warning"message: a string containing the actual messageImage convertersAn image converter can be created by callingmammoth.images.img_element(func). This creates an<img>element
for each image in the original docx.funcshould be a function that
has one argumentimage. This argument is the image element being
converted, and has the following properties:open(): open the image file. Returns a file-like object.content_type: the content type of the image, such asimage/png.funcshould return adictof attributes for the<img>element. At a minimum, this should include thesrcattribute. If any
alt text is found for the image, this will be automatically added to the
element’s attributes.For instance, the following replicates the default image conversion:defconvert_image(image):withimage.open()asimage_bytes:encoded_src=base64.b64encode(image_bytes.read()).decode("ascii")return{"src":"data:{0};base64,{1}".format(image.content_type,encoded_src)}mammoth.images.img_element(convert_image)mammoth.images.data_uriis the default image converter.WMF images are not handled by default by Mammoth. The recipes directory
containsan example of how they can be converted using
LibreOffice,
although the fidelity of the conversion depends entirely on LibreOffice.Document transformsThe API for document transforms should be considered unstable, and may
change between any versions. If you rely on this behaviour, you should
pin to a specific version of Mammoth, and test carefully before
updating.Mammoth allows a document to be transformed before it is converted. For
instance, suppose that document has not been semantically marked up, but
you know that any centre-aligned paragraph should be a heading. You can
use thetransform_documentargument to modify the document
appropriately:importmammoth.transformsdeftransform_paragraph(element):ifelement.alignment=="center"andnotelement.style_id:returnelement.copy(style_id="Heading2")else:returnelementtransform_document=mammoth.transforms.paragraph(transform_paragraph)mammoth.convert_to_html(fileobj,transform_document=transform_document)Or if you want paragraphs that have been explicitly set to use monospace
fonts to represent code:importmammoth.documentsimportmammoth.transforms_monospace_fonts=set(["consolas","courier","courier new"])deftransform_paragraph(paragraph):runs=mammoth.transforms.get_descendants_of_type(paragraph,mammoth.documents.Run)ifrunsandall(run.fontandrun.font.lower()in_monospace_fontsforruninruns):returnparagraph.copy(style_id="code",style_name="Code")else:returnparagraphconvert_to_html(fileobj,transform_document=mammoth.transforms.paragraph(transform_paragraph),style_map="p[style-name='Code'] => pre:separator('\n')",)mammoth.transforms.paragraph(transform_paragraph)Returns a function that can be used as thetransform_documentargument. This will apply the functiontransform_paragraphto each
paragraph element.transform_paragraphshould return the new
paragraph.mammoth.transforms.run(transform_run)Returns a function that can be used as thetransform_documentargument. This will apply the functiontransform_runto each run
element.transform_runshould return the new run.mammoth.transforms.get_descendants(element)Gets all descendants of an element.mammoth.transforms.get_descendants_of_type(element, type)Gets all descendants of a particular type of an element. For instance,
to get all runs within an elementparagraph:importmammoth.documentsimportmammoth.transformsruns=mammoth.transforms.get_descendants_of_type(paragraph,documents.Run);Writing style mapsA style map is made up of a number of style mappings separated by new
lines. Blank lines and lines starting with#are ignored.A style mapping has two parts:On the left, before the arrow, is the document element matcher.On the right, after the arrow, is the HTML path.When converting each paragraph, Mammoth finds the first style mapping
where the document element matcher matches the current paragraph.
Mammoth then ensures the HTML path is satisfied.FreshnessWhen writing style mappings, it’s helpful to understand Mammoth’s notion
of freshness. When generating, Mammoth will only close an HTML element
when necessary. Otherwise, elements are reused.For instance, suppose one of the specified style mappings isp[style-name='Heading1'] => h1. If Mammoth encounters a .docx
paragraph with the style nameHeading 1, the .docx paragraph is
converted to ah1element with the same text. If the next .docx
paragraph also has the style nameHeading 1, then the text of that
paragraph will be appended to theexistingh1element, rather than
creating a newh1element.In most cases, you’ll probably want to generate a newh1element
instead. You can specify this by using the:freshmodifier:p[style-name='Heading1'] => h1:freshThe two consecutiveHeading 1.docx paragraphs will then be
converted to two separateh1elements.Reusing elements is useful in generating more complicated HTML
structures. For instance, suppose your .docx contains asides. Each aside
might have a heading and some body text, which should be contained
within a singlediv.asideelement. In this case, style mappings
similar top[style-name='AsideHeading'] => div.aside > h2:freshandp[style-name='AsideText'] => div.aside > p:freshmight be helpful.Document element matchersParagraphs, runs and tablesMatch any paragraph:pMatch any run:rMatch any table:tableTo match a paragraph, run or table with a specific style, you can
reference the style by name. This is the style name that is displayed in
Microsoft Word or LibreOffice. For instance, to match a paragraph with
the style nameHeading 1:p[style-name='Heading 1']You can also match a style name by prefix. For instance, to match a
paragraph where the style name starts withHeading:p[style-name^='Heading']Styles can also be referenced by style ID. This is the ID used
internally in the .docx file. To match a paragraph or run with a
specific style ID, append a dot followed by the style ID. For instance,
to match a paragraph with the style IDHeading1:p.Heading1BoldMatch explicitly bold text:bNote that this matches text that has had bold explicitly applied to it.
It will not match any text that is bold because of its paragraph or run
style.ItalicMatch explicitly italic text:iNote that this matches text that has had italic explicitly applied to
it. It will not match any text that is italic because of its paragraph
or run style.UnderlineMatch explicitly underlined text:uNote that this matches text that has had underline explicitly applied to
it. It will not match any text that is underlined because of its
paragraph or run style.StrikethoughMatch explicitly struckthrough text:strikeNote that this matches text that has had strikethrough explicitly
applied to it. It will not match any text that is struckthrough because
of its paragraph or run style.All capsMatch explicitly all caps text:all-capsNote that this matches text that has had all caps explicitly applied to
it. It will not match any text that is all caps because of its paragraph
or run style.Small capsMatch explicitly small caps text:small-capsNote that this matches text that has had small caps explicitly applied
to it. It will not match any text that is small caps because of its
paragraph or run style.Ignoring document elementsUse!to ignore a document element. For instance, to ignore any
paragraph with the styleComment:p[style-name='Comment'] => !HTML pathsSingle elementsThe simplest HTML path is to specify a single element. For instance, to
specify anh1element:h1To give an element a CSS class, append a dot followed by the name of the
class:h1.section-titleTo add an attribute, use square brackets similarly to a CSS attribute
selector:p[lang='fr']To require that an element is fresh, use:fresh:h1:freshModifiers must be used in the correct order:h1.section-title:freshSeparatorsTo specify a separator to place between the contents of paragraphs that
are collapsed together, use:separator('SEPARATORSTRING').For instance, suppose a document contains a block of code where each
line of code is a paragraph with the styleCode Block. We can write
a style mapping to map such paragraphs to<pre>elements:p[style-name='Code Block'] => preSincepreisn’t marked as:fresh, consecutivepreelements
will be collapsed together. However, this results in the code all being
on one line. We can use:separatorto insert a newline between each
line of code:p[style-name='Code Block'] => pre:separator('\n')Nested elementsUse>to specify nested elements. For instance, to specifyh2withindiv.aside:div.aside > h2You can nest elements to any depth.DonationsIf you’d like to say thanks, feel free tomake a donation through
Ko-fi.If you use Mammoth as part of your business, please consider supporting
the ongoing maintenance of Mammoth bymaking a weekly donation through
Liberapay.