[英]html-docx-js is not abe to apply external css class styles when it creates docx file
Using html-docx-js module, I am able to covert html content into docx format.使用 html-docx-js 模块,我能够将 html 内容转换为 docx 格式。 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.
但是我遇到了一个问题,我的大部分 css 都是从外部加载的,而 html-docx-js 没有应用它的任何样式。
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.有人建议使用juice library,但这也不起作用。
Would anyone know if there is a work around to get html-docx-js to load external css when creating docx file?有谁知道在创建 docx 文件时是否有办法让 html-docx-js 加载外部 css?
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 的模块,它允许内联应用指定的css。
Juice needs a copy of css, which I had to separetely load. Juice 需要一份 css 副本,我不得不单独加载。
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.此外,由于 html-docx-js 只能读取元素中的第一个 css 样式定义,因此我不得不稍微调整 css 和 html 以适应它。
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.您可以在head标签中使用CSS 类,但必须同时选择元素标签和类名。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.