privateOmega / html-to-docx

HTML to DOCX converter
MIT License
373 stars 140 forks source link

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

Open SystemError7 opened 11 months ago

SystemError7 commented 11 months ago

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

Mtillmann commented 10 months ago

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

nicolasiscoding commented 10 months ago

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

Mtillmann commented 10 months ago

@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 commented 10 months ago

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