我想将 html 字符串保存为 docx 文件。我尝试了两个库:Blob 和 html-docx-js
- 使用 Blob,我无法使用 MS Office 打开生成的文件,但我可以使用 LibreOffice 打开它。图像按预期插入。我怀疑我在这条线上做错了什么
var converted = new Blob(['\ufeff', htmlString], {type: 'application/msword' })
- 使用 hmtl-docx-js,我面临 2 个问题:
生成的docx文件不能用LibreOffice打开,但可以用MS Office打开。PS:LibreOffice可以打开普通的docx文件。所以生成的文件肯定有问题。
htmlDocx 不插入图像。我阅读了文档,但我真的不知道如何处理它。
querySelectorAll('img')
显然不能在字符串变量上调用。
这是我的代码
import htmlDocx from 'html-docx-js/dist/html-docx';
import { saveAs } from 'file-saver'
var Blob = require('blob');
...
async saveFile(e){
e.preventDefault();
var htmlString = this.state.html;
var preHtml = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8">
<title>Export HTML To Doc</title><style> body,html
{margin-top: 0px !important;
padding-top: 0px !important;
padding-left: 0px !important;
margin-left: 0px !important;
font-size: 12px;
margin-left: 0px !important;
}.
scheduledtxt{font-size: 14.5px;} table{margin: auto 0px !important;}</head><body>`;
htmlString = preHtml + htmlString +`</body></html>`;
var converted = new Blob(['\ufeff', htmlString], {type: 'application/msword' })
// var converted = htmlDocx.asBlob(htmlString)
saveAs(converted, 'test.docx');
}
...