Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
SystemError7 opened this issue Oct 10, 2023 · 4 comments
Open

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

SystemError7 opened this issue Oct 10, 2023 · 4 comments

Comments

@SystemError7
Copy link

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 SystemError7 changed the title Images & Font error Images & style doesn't apply well in .docx file Oct 10, 2023
@Mtillmann
Copy link

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
Copy link
Contributor

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

@Mtillmann
Copy link

@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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants