html-to-docx
html-to-docx copied to clipboard
Images & style doesn't apply well in .docx file
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.
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 if you have any bandwidth, can you write a short example of this? I think it can be helpful to the community
@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>
the example assumes node >=18 with top level await and a module environment. It works very similar with other environments