[英]html-docx-js is not abe to apply external css class styles when it creates docx file
使用 html-docx-js 模塊,我能夠將 html 內容轉換為 docx 格式。 但是我遇到了一個問題,我的大部分 css 都是從外部加載的,而 html-docx-js 沒有應用它的任何樣式。
簡化代碼示例:
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');
有人建議使用juice library,但這也不起作用。
有誰知道在創建 docx 文件時是否有辦法讓 html-docx-js 加載外部 css?
經過一番研究后,我找到了解決我的問題的可行方法:
有一個名為juice 的模塊,它允許內聯應用指定的css。
Juice 需要一份 css 副本,我不得不單獨加載。
此外,由於 html-docx-js 只能讀取元素中的第一個 css 樣式定義,因此我不得不稍微調整 css 和 html 以適應它。
最終代碼如下所示:
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);
});
您可以在head標簽中使用CSS 類,但必須同時選擇元素標簽和類名。
它看起來像這樣:
<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.