html-to-docx icon indicating copy to clipboard operation
html-to-docx copied to clipboard

Images & style doesn't apply well in .docx file

Open SystemError7 opened this issue 10 months ago • 4 comments

I tried to do a simple conversion to a docx file and I opened the file with LibreOffice and I see that the css doesn´t apply well, it generated like a str. Also, the image have been generated like a string instead of the image it's self. image

SystemError7 avatar Oct 10 '23 07:10 SystemError7

To use CSS you can use https://www.npmjs.com/package/inline-css to inline your styles before you convert to docx. This will keep at least some of your style in your document. It'll also remove the style and link elements

Mtillmann avatar Oct 29 '23 19:10 Mtillmann

@Mtillmann if you have any bandwidth, can you write a short example of this? I think it can be helpful to the community

nicolasiscoding avatar Oct 29 '23 20:10 nicolasiscoding

@nicolasiscoding , sure:

import HTMLtoDOCX from 'html-to-docx';
import InlineCss from 'inline-css';

const rawHTMLStringWithStyle = `
<style>
    .sans-serif{
        font-family: sans-serif;
    }
    .center{
        text-align:center;
    }
    p{
        margin-bottom:1.5rem;
    }
</style>

<div class="sans-serif">
    <h1 class="center">Text, centered</h1>
    <p>A simple paragraph that will receive margin bottom from the element selector</p>
</div>
`;

const inlinedHTML = await InlineCss(rawHTMLStringWithStyle, { url: 'file://' });

const docxWithStyles = await HTMLtoDOCX(inlinedHTML);

//... your code

inlinedHTML will contain this html with the styles applied to the nodes:

<html>
<head>
</head>
<body>
    <div class="sans-serif" style="font-family: sans-serif;">
        <h1 class="center" style="text-align: center;">Text, centered</h1>
        <p style="margin-bottom: 1.5rem;">A simple paragraph that will receive margin bottom from the element selector
        </p>
    </div>
</body>
</html>

Mtillmann avatar Oct 29 '23 20:10 Mtillmann

the example assumes node >=18 with top level await and a module environment. It works very similar with other environments

Mtillmann avatar Oct 29 '23 20:10 Mtillmann