Using html-docx-js module, I am able to covert html content into docx format. However I am running into an issue where most of my css is loaded externally and html-docx-js does not apply any of its styles.
Simplified code sample:
const html = '<html><head><link rel="stylesheet" type="text/css" href="/styles/page.css"></head><body><div className={bold}>I am bold!</div></body></html>'
saveAs(htmlDocx.asBlob(html), 'bold.docx');
It was suggested to use juice library, however that did not work either.
Would anyone know if there is a work around to get html-docx-js to load external css when creating docx file?
After doing a bit a research I found a working solution to my problem(s):
There is a module called juice, which allows to apply specified css inline.
Juice needs a copy of css, which I had to separetely load.
Also since html-docx-js can only read only first css style definition within an element, I had to slightly adjust css and html to accommodate that.
Final code looks like this:
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
const juice = require('juice');
let getIndex = new Promise((resolve, reject) => {
this.requests('GET', '/styles/index.css')
.then(data =>
data.text().then(css => {
resolve(css);
})
)
.catch(error => reject(error));
});
getIndex
.then(css => {
let html =
'<!DOCTYPE html><html><head lang="en"><style></style>' +
'<meta charset="UTF-8"><title>Report</title></head><body>' +
this.report.innerHTML +
'</body></html>';
html = juice.inlineContent(html, css);
let docx = htmlDocx.asBlob(html);
saveAs(docx, 'report.docx');
})
.catch(error => {
console.log(error);
});
You can use a CSS class in the head tag, but you must select the element tag and the classname together.
It looks like this:
<head>
...
<style type="text/css">
div.MyCustomClass {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
</style>
</head>
<body>
...
<div class="MyCustomClass">
...
</div>
</body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.