This version of the module is deprecated: Use moonbitlang/docx2html instead

    docx2html

    Native MoonBit DOCX to HTML/Markdown converter ported from Mammoth

    docx
    html
    markdown
    mammoth
    Download zip
    Author
    Version
    0.1.27
    License
    Apache-2.0
    Last updated
    5 months ago
    Downloads
    808

    #bobzhang/docx2html

    Native MoonBit DOCX reader and converter, ported from Mammoth. The current focus is the common docx -> html, docx -> markdown, and raw-text paths with Mammoth-compatible diagnostics where the JavaScript library exposes them.

    #Install

    moon add bobzhang/docx2html

    #Usage

    ///|
    test "convert document model to html" {
    let doc = @docx2html.document([
    @docx2html.paragraph([@docx2html.text("Hello.")]),
    ])
    let result = @docx2html.convert_document_to_html(doc)
    inspect(result.value, content="<p>Hello.</p>")
    }

    For DOCX bytes, use convert_to_html, convert_to_markdown, or extract_raw_text. The native API accepts BytesView, so callers can decide how to load files. External linked images stay disabled by default, matching Mammoth; pass external_file_access=true and a read_external_file callback when the source document is allowed to read sibling files.

    #Document Model

    The document model exposes enum constructors for pattern matching and lower-snake helpers for building nodes and property records:

    ///|
    test "build document model with helpers" {
    let doc = @docx2html.document([
    @docx2html.paragraph(
    [
    @docx2html.hyperlink(
    [@docx2html.text("MoonBit")],
    href=Some("https://www.moonbitlang.com"),
    ),
    ],
    properties=@docx2html.paragraph_properties(style_name=Some("Heading 1")),
    ),
    @docx2html.table([
    @docx2html.table_row([
    @docx2html.table_cell([@docx2html.paragraph([@docx2html.text("Cell")])]),
    ]),
    ]),
    ])
    let result = @docx2html.convert_document_to_html(doc, style_map=[
    "p[style-name='Heading 1'] => h2",
    ])
    inspect(
    result.value,
    content="<h2><a href=\"https://www.moonbitlang.com\">MoonBit</a></h2><table><tr><td><p>Cell</p></td></tr></table>",
    )
    }

    Embedded style maps can be inspected or rewritten without a JavaScript-style mutable ZIP object. Use read_embedded_style_map(docx[:]) to read the raw mammoth/style-map part, and embed_style_map(docx[:], "p => h1") to return a new DOCX archive with the style map, relationship entry, and content-type override updated.

    #Transforms

    Document transforms run before conversion and recurse through child-bearing nodes. Use the typed helpers instead of Mammoth's JavaScript string type names:

    ///|
    test "transform runs before conversion" {
    let doc = @docx2html.document([
    @docx2html.paragraph([@docx2html.run([@docx2html.text("Hello.")])]),
    ])
    let transform_document = @docx2html.transform_runs(fn(_run) {
    @docx2html.run([@docx2html.text("Goodbye.")])
    })
    let result = @docx2html.convert_document_to_html(doc, transform_document~)
    inspect(result.value, content="<p>Goodbye.</p>")
    let runs = @docx2html.document_descendants_where(doc, fn(element) {
    element is Run(..)
    })
    inspect(runs.length(), content="1")
    }

    #Native CLI

    From this repository checkout, the native executable mirrors the common Mammoth CLI paths:

    moon run --target native cmd/main -- input.docx moon run --target native cmd/main -- --output-format=markdown input.docx moon run --target native cmd/main -- --style-map style-map input.docx output.html moon run --target native cmd/main -- --output-dir out input.docx

    #Image Conversion

    Images are emitted as data URIs by default. Pass convert_image to override that behavior. data_uri_image is the default converter, and inline_image is the MoonBit name for Mammoth's images.inline/images.imgElement helper:

    ///|
    test "custom image conversion" {
    let image = @docx2html.Image::{
    content_type: "image/png",
    alt_text: Some("chart"),
    data: b"abc",
    }
    let doc = @docx2html.document([@docx2html.paragraph([Image(image)])])
    let convert_image = @docx2html.inline_image(fn(_image) {
    { "src": "/assets/chart.png" }
    })
    let result = @docx2html.convert_document_to_html(doc, convert_image~)
    inspect(
    result.value,
    content="<p><img alt=\"chart\" src=\"/assets/chart.png\" /></p>",
    )
    }

    #Results

    Conversion results carry rendered text plus diagnostics. Use combine_results when stitching several conversion fragments together:

    ///|
    test "combine conversion results" {
    let combined = @docx2html.combine_results([
    @docx2html.success("One"),
    { value: "Two", messages: [Warning("same")] },
    { value: "Three", messages: [Warning("same")] },
    ])
    inspect(combined.value, content="OneTwoThree")
    debug_inspect(combined.messages, content="[Warning(\"same\")]")
    }

    #Status

    This is an active port. The native core and carried Mammoth parity tests are green, but the broader Mammoth public surface is still being expanded.

    DocxError

    pub(all) suberror DocxError {
    InvalidZip(String)
    InvalidXml(String)
    MissingPart(String)
    Unsupported(String)
    } derive(Eq,
    Debug
    )

    BreakType

    pub(all) enum BreakType {
    Line
    Page
    Column
    } derive(Eq,
    Debug
    )

    Comment

    pub(all) struct Comment {
    comment_id : String
    body : Array[DocumentElement]
    author_name : String
    author_initials : String
    } derive(Eq,
    Debug
    )

    ConversionResult

    pub(all) struct ConversionResult {
    value : String
    messages : Array[Message]
    } derive(Eq,
    Debug
    )

    ConversionResult::combine

    ConversionResult::flat_map

    fn ConversionResult::flat_map(self : ConversionResult, f : (String) -> ConversionResult raise?) -> ConversionResult raise?

    ConversionResult::map

    fn ConversionResult::map(self : ConversionResult, f : (String) -> String raise?) -> ConversionResult raise?

    DocumentElement

    pub(all) enum DocumentElement {
    Document(Array[DocumentElement], Array[Note], Array[Comment])
    Paragraph(Array[DocumentElement], ParagraphProperties)
    Run(Array[DocumentElement], RunProperties)
    Text(String)
    Tab
    Checkbox(Bool)
    Hyperlink(Array[DocumentElement], String?, String?, String?)
    NoteReference(String, String)
    CommentReference(String)
    Image(Image)
    Table(Array[DocumentElement], TableProperties)
    TableRow(Array[DocumentElement], Bool)
    TableCell(Array[DocumentElement], Int, Int)
    Break(BreakType)
    BookmarkStart(String)
    } derive(Eq,
    Debug
    )

    DocumentElement::to_raw_text

    fn DocumentElement::to_raw_text(self : DocumentElement) -> String

    DocumentMatcher

    pub(all) enum DocumentMatcher {
    ParagraphMatcher(String?, StyleNameMatcher?, Numbering?)
    RunMatcher(String?, StyleNameMatcher?)
    RunPropertyMatcher(String)
    HighlightMatcher(String?)
    TableMatcher(String?, StyleNameMatcher?)
    BreakMatcher(BreakType)
    CommentReferenceMatcher
    } derive(Eq,
    Debug
    )

    HtmlNode

    pub(all) enum HtmlNode {
    Element(String, Map[String, String], Array[HtmlNode], Bool, String?)
    TextNode(String)
    ForceWrite
    } derive(Eq,
    Debug
    )

    HtmlPathElement

    pub(all) struct HtmlPathElement {
    tag : String
    attributes : Map[String, String]
    fresh : Bool
    separator : String?
    } derive(Eq,
    Debug
    )

    Image

    pub(all) struct Image {
    content_type : String
    alt_text : String?
    data : Bytes
    } derive(Eq,
    Debug
    )

    ImageConversion

    pub(all) struct ImageConversion {
    nodes : Array[HtmlNode]
    messages : Array[Message]
    } derive(Eq,
    Debug
    )

    Indent

    pub(all) struct Indent {
    start : String?
    end : String?
    first_line : String?
    hanging : String?
    } derive(Eq,
    Debug
    )

    Indent::default

    fn Indent::default() -> Indent

    Message

    pub(all) enum Message {
    Warning(String)
    Error(String)
    } derive(Eq,
    Debug
    )

    Note

    pub(all) struct Note {
    note_type : String
    note_id : String
    body : Array[DocumentElement]
    } derive(Eq,
    Debug
    )

    Numbering

    pub(all) struct Numbering {
    is_ordered : Bool
    level : Int
    } derive(Eq,
    Debug
    )

    ParagraphProperties

    pub(all) struct ParagraphProperties {
    style_id : String?
    style_name : String?
    numbering : Numbering?
    alignment : String?
    indent : Indent
    } derive(Eq,
    Debug
    )

    ParagraphProperties::default

    RunProperties

    pub(all) struct RunProperties {
    style_id : String?
    style_name : String?
    is_bold : Bool
    is_underline : Bool
    is_italic : Bool
    is_strikethrough : Bool
    is_all_caps : Bool
    is_small_caps : Bool
    vertical_alignment : VerticalAlignment
    font : String?
    font_size : Int?
    highlight : String?
    } derive(Eq,
    Debug
    )

    RunProperties::default

    fn RunProperties::default() -> RunProperties

    StyleMapping

    pub(all) struct StyleMapping {
    from : DocumentMatcher
    to : Array[HtmlPathElement]
    } derive(Eq,
    Debug
    )

    StyleNameMatcher

    pub(all) enum StyleNameMatcher {
    ExactStyleName(String)
    PrefixStyleName(String)
    } derive(Eq,
    Debug
    )

    TableProperties

    pub(all) struct TableProperties {
    style_id : String?
    style_name : String?
    } derive(Eq,
    Debug
    )

    TableProperties::default

    VerticalAlignment

    pub(all) enum VerticalAlignment {
    Baseline
    Superscript
    Subscript
    } derive(Eq,
    Debug
    )

    XmlElement

    pub(all) struct XmlElement {
    name : String
    attributes : Map[String, String]
    children : Array[XmlNode]
    } derive(Eq,
    Debug
    )

    XmlElement::descendants_by_tag_name

    fn XmlElement::descendants_by_tag_name(self : XmlElement, name : String) -> Array[XmlElement]

    XmlElement::elements_by_tag_name

    fn XmlElement::elements_by_tag_name(self : XmlElement, name : String) -> Array[XmlElement]

    XmlElement::first

    fn XmlElement::first(self : XmlElement, name : String) -> XmlElement?

    XmlElement::first_or_empty

    fn XmlElement::first_or_empty(self : XmlElement, name : String) -> XmlElement

    XmlElement::text

    fn XmlElement::text(self : XmlElement) -> String raise DocxError

    XmlNode

    pub(all) enum XmlNode {
    XmlElement(XmlElement)
    XmlText(String)
    } derive(Eq,
    Debug
    )

    ZipArchive

    pub(all) struct ZipArchive {
    entries : Map[String, Bytes]
    } derive(Eq,
    Debug
    )

    ZipArchive::exists

    fn ZipArchive::exists(self : ZipArchive, path : String) -> Bool

    ZipArchive::read_bytes

    fn ZipArchive::read_bytes(self : ZipArchive, path : String) -> Bytes?

    ZipArchive::read_text

    fn ZipArchive::read_text(self : ZipArchive, path : String) -> String? raise DocxError

    bookmark_start

    fn bookmark_start(name : String) -> DocumentElement

    checkbox

    fn checkbox(checked : Bool) -> DocumentElement

    column_break

    fn column_break() -> DocumentElement

    combine_results

    fn combine_results(results : Array[ConversionResult]) -> ConversionResult

    comment

    fn comment(comment_id : String, body : Array[DocumentElement], author_name? : String, author_initials? : String) -> Comment

    comment_reference

    fn comment_reference(comment_id : String) -> DocumentElement

    convert_document_to_html

    fn convert_document_to_html(document : DocumentElement, style_map? : Array[String], include_default_style_map? : Bool, ignore_empty_paragraphs? : Bool, id_prefix? : String, pretty_print? : Bool, convert_image? : (Image) -> ImageConversion, transform_document? : (DocumentElement) -> DocumentElement) -> ConversionResult

    convert_document_to_markdown

    fn convert_document_to_markdown(document : DocumentElement, style_map? : Array[String], include_default_style_map? : Bool, ignore_empty_paragraphs? : Bool, id_prefix? : String, convert_image? : (Image) -> ImageConversion, transform_document? : (DocumentElement) -> DocumentElement) -> ConversionResult

    convert_to_html

    fn convert_to_html(docx : BytesView, style_map? : Array[String], include_default_style_map? : Bool, include_embedded_style_map? : Bool, ignore_empty_paragraphs? : Bool, id_prefix? : String, pretty_print? : Bool, convert_image? : (Image) -> ImageConversion, transform_document? : (DocumentElement) -> DocumentElement, external_file_access? : Bool, read_external_file? : (String) -> Bytes?) -> ConversionResult raise DocxError

    convert_to_markdown

    fn convert_to_markdown(docx : BytesView, style_map? : Array[String], include_default_style_map? : Bool, include_embedded_style_map? : Bool, ignore_empty_paragraphs? : Bool, id_prefix? : String, convert_image? : (Image) -> ImageConversion, transform_document? : (DocumentElement) -> DocumentElement, external_file_access? : Bool, read_external_file? : (String) -> Bytes?) -> ConversionResult raise DocxError

    data_uri_image

    fn data_uri_image(image : Image) -> ImageConversion

    data_uri_image_converter

    fn data_uri_image_converter(image : Image) -> ImageConversion

    default_style_map_lines

    fn default_style_map_lines() -> Array[String]

    document

    fn document(children : Array[DocumentElement], notes? : Array[Note], comments? : Array[Comment]) -> DocumentElement

    document_descendants

    fn document_descendants(element : DocumentElement) -> Array[DocumentElement]

    document_descendants_where

    fn document_descendants_where(element : DocumentElement, predicate : (DocumentElement) -> Bool) -> Array[DocumentElement]

    embed_style_map

    fn embed_style_map(docx : BytesView, style_map : String) -> Bytes raise DocxError

    error

    fn error(message : String) -> Message

    escape_html

    fn escape_html(value : String) -> String

    escape_html_attribute

    fn escape_html_attribute(value : String) -> String

    escape_markdown_text

    fn escape_markdown_text(value : String) -> String

    extract_raw_text

    fn extract_raw_text(docx : BytesView, external_file_access? : Bool, read_external_file? : (String) -> Bytes?) -> ConversionResult raise DocxError

    extract_raw_text_from_document

    fn extract_raw_text_from_document(document : DocumentElement) -> ConversionResult

    fresh_html_element

    fn fresh_html_element(tag : String, attributes? : Map[String, String], children? : Array[HtmlNode], separator? : String) -> HtmlNode

    html_element

    fn html_element(tag : String, attributes? : Map[String, String], children? : Array[HtmlNode], fresh? : Bool, separator? : String) -> HtmlNode

    html_text

    fn html_text(value : String) -> HtmlNode

    fn hyperlink(children : Array[DocumentElement], href? : String?, anchor? : String?, target_frame? : String?) -> DocumentElement

    identity_document_transform

    fn identity_document_transform(element : DocumentElement) -> DocumentElement

    image

    fn image(content_type : String, data : Bytes, alt_text? : String?) -> DocumentElement

    image_conversion

    fn image_conversion(nodes : Array[HtmlNode], messages? : Array[Message]) -> ImageConversion

    img_element

    fn img_element(read_attributes : (Image) -> Map[String, String]) -> ((Image) -> ImageConversion)

    indent

    fn indent(start? : String?, end? : String?, first_line? : String?, hanging? : String?) -> Indent

    inline_image

    fn inline_image(read_attributes : (Image) -> Map[String, String]) -> ((Image) -> ImageConversion)

    join_zip_path

    fn join_zip_path(parts : Array[String]) -> String

    line_break

    fn line_break() -> DocumentElement

    note

    fn note(note_type : String, note_id : String, body : Array[DocumentElement]) -> Note

    note_reference

    fn note_reference(note_type : String, note_id : String) -> DocumentElement

    numbering

    fn numbering(is_ordered : Bool, level : Int) -> Numbering

    open_zip

    fn open_zip(data : BytesView) -> ZipArchive raise DocxError

    page_break

    fn page_break() -> DocumentElement

    paragraph

    fn paragraph(children : Array[DocumentElement], properties? : ParagraphProperties) -> DocumentElement

    paragraph_properties

    fn paragraph_properties(style_id? : String?, style_name? : String?, numbering? : Numbering?, alignment? : String?, indent? : Indent) -> ParagraphProperties

    read_docx

    fn read_docx(docx : BytesView, external_file_access? : Bool, read_external_file? : (String) -> Bytes?) -> DocumentElement raise DocxError

    read_embedded_style_map

    fn read_embedded_style_map(docx : BytesView) -> String? raise DocxError

    read_style_map

    fn read_style_map(lines : Array[String]) -> Array[StyleMapping]

    read_style_map_string

    fn read_style_map_string(style_map : String) -> Array[String]

    read_style_mapping

    fn read_style_mapping(line : String) -> StyleMapping?

    read_xml_string

    fn read_xml_string(source : String, namespace_map? : Map[String, String]) -> XmlElement raise DocxError

    run

    fn run(children : Array[DocumentElement], properties? : RunProperties) -> DocumentElement

    run_properties

    fn run_properties(style_id? : String?, style_name? : String?, is_bold? : Bool, is_underline? : Bool, is_italic? : Bool, is_strikethrough? : Bool, is_all_caps? : Bool, is_small_caps? : Bool, vertical_alignment? : VerticalAlignment, font? : String?, font_size? : Int?, highlight? : String?) -> RunProperties

    simplify_html

    fn simplify_html(nodes : Array[HtmlNode]) -> Array[HtmlNode]

    split_zip_path

    fn split_zip_path(path : String) -> (String, String)

    success

    fn success(value : String) -> ConversionResult

    tab

    fn tab() -> DocumentElement

    table

    fn table(children : Array[DocumentElement], properties? : TableProperties) -> DocumentElement

    table_cell

    fn table_cell(children : Array[DocumentElement], col_span? : Int, row_span? : Int) -> DocumentElement

    table_properties

    fn table_properties(style_id? : String?, style_name? : String?) -> TableProperties

    table_row

    fn table_row(children : Array[DocumentElement], is_header? : Bool) -> DocumentElement

    text

    fn text(value : String) -> DocumentElement

    transform_elements

    fn transform_elements(element : DocumentElement, transform : (DocumentElement) -> DocumentElement) -> DocumentElement

    transform_paragraphs

    fn transform_paragraphs(transform : (DocumentElement) -> DocumentElement) -> ((DocumentElement) -> DocumentElement)

    transform_runs

    fn transform_runs(transform : (DocumentElement) -> DocumentElement) -> ((DocumentElement) -> DocumentElement)

    warning

    fn warning(message : String) -> Message

    write_html

    fn write_html(nodes : Array[HtmlNode], pretty_print? : Bool) -> String

    write_markdown

    fn write_markdown(nodes : Array[HtmlNode]) -> String

    write_xml_string

    fn write_xml_string(root : XmlElement, namespaces? : Map[String, String]) -> String

    xml_element

    fn xml_element(name : String, attributes? : Map[String, String], children? : Array[XmlNode]) -> XmlElement

    xml_text

    fn xml_text(value : String) -> XmlNode