Search code examples
pythonmammoth

Using Mammoth style_map to apply inline styles and custom attributes


I'd like to use Mammoth's style map to apply inline styles, like color:red and custom tags/attributes, though I cannot seem to find anything in the docs that suggest I can. Does mammoth have the capability to do inline styling?

Simple tags and classes works fine, e.g. p[style-name='Heading 3'] => div.foo:fresh

However I'd like to do something like this: p[style-name='Heading 3'] => div(color:red):fresh or p[style-name='Heading 3'] => div, cust_tag:val:fresh


Solution

  • I had the same trouble. The author of the library seems pretty uninterested in adding in-line styles as well. The trick is to just add a class using the mapping you're referring to, then later parse out that particular class and apply the in-line styles.

    For example, here I've assigned classes to aligned text, 'left-aligned' and 'right-aligned'. Then from the MammothJS result, I run it through this function to get the class -> in-line style conversion.

    function transformHTML(html) {
        const doc = new DOMParser().parseFromString(html, "text/html");
        doc.querySelectorAll("[class]").forEach((el) => {
            const classes = el.getAttribute("class").split(" ");
            const style = classes.reduce((acc, className) => {
    
            // Add additional cases to handle other classes as needed
            switch (className) {
                case "left-aligned":
                    return acc + "text-align: left;";
                case "center-aligned":
                    return acc + "text-align: center;";
                case "right-aligned":
                    return acc + "text-align: right;";
                default:
                    return acc;
            }
    
            }, "");
            el.removeAttribute("class");
            el.setAttribute("style", style);
        });
        return doc.documentElement.innerHTML;
    }