【发布时间】:2020-03-30 17:54:55
【问题描述】:
这是客户端代码,它是最小的、完整的和可验证的 sn-p,它允许其他开发人员自行测试。
// requires: a string that contains html tags
// returns: a word document that can be downloaded with extension .doc or docx
// @ param cvAsHTML is a string that contains html tags
const preHtml = "<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/html4/loose.dtd\'><head><meta charset='utf-8'></head><body>";
const postHtml = "</body></html>";
const html = preHtml + cvAsHTML + postHtml;
let filename = "filename";
const blob = new Blob(["\ufeff", html], { type: "application/msword"});
上面的 sn-p 就像一个魅力。请注意,XML 模式是多余的,实际上是不必要的。 doc 文件可以在没有它们的情况下工作,但必须存在 head 和 body 标签。
对于docx 文件,我无法下载该文件。该文件似乎已损坏,经过几次试验,我真的不知道该怎么办。这是 docx 文件的代码:
const preHtml = "<?xml version='1.0' encoding='UTF-8?><html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/html4/loose.dtd\'><head><meta charset='utf-8'></head><body>";
const postHtml = "</body></html>";
const html = preHtml + cvAsHTML + postHtml;
let filename = "filename.docx";
const blob = new Blob(["\ufeff", html], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main"});
注意:我已更改 Blob 对象内的 MIME 类型,并尝试了不同的其他选项,例如 application/zip、application/octet-stream 等,但均无济于事。我还更改了 prehtml 变量以包括:
<?xml version='1.0' encoding='UTF-8?>
鉴于我了解 docx 文件本质上是包含 xml 段的压缩文件...
非常感谢您提供的任何帮助。
编辑:2019 年 12 月 16 日
这是我在@dw_建议的实现后截取的截图:
使用JSZip 的实现无法按预期工作,因为:
- 浏览器本身不允许用户在 microsoft word 中打开文件,就像使用
doc文件一样; - 用户必须先保存文件,但即便如此,文件也无法打开,因为它已损坏。
【问题讨论】:
标签: javascript xml file blob docx