HTML-DOCX-JS在创建DOCX文件时不适用于应用外部CSS类样式



使用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');

建议使用果汁库,但这也不起作用。

有人会知道是否有工作要使HTML-DOCX-JS在创建DOCX文件时加载外部CSS?

做了一些研究后,我找到了解决问题的解决方案:

有一个称为Juice的模块,该模块允许使用指定的CSS内联。

果汁需要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 class ,但是您必须选择 element tag className 一起。

看起来像这样:

<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>

最新更新