html-docx-js-typescript源码:GitHub - caiyexiang/html-docx-js-typescript: Convert HTML documents to docx format.
html-docx-js地址:html-docx-js - npm
*简单使用:
获取需要转为word文档的html节点,借助file-saver提供的saveAs方法和html-docx-js提供的asBlob方法转换我们设置好的html即可。
简单使用: import htmlDocx from "html-docx-js/dist/html-docx"; import { saveAs } from "file-saver"; import $ from "jquery"; function exportWord(dom, fileName) { setTimeout(() => { let htmlStr = ` <!DOCTYPE html> <html lang="en"> <body style="font-family:方正仿宋_GBK;mso-ascii-font-family:'Times New Roman'"> ${dom.html()} </body> </html> `; saveAs( htmlDocx.asBlob(htmlStr, { orientation: "landscape" }), fileName ); }, 200); } |
*demo示例:
包含图片( echarts可直接通过自带的方法.getConnectedDataURL({ type: "png" })
获取base64)
// img图片转换base64 // 结构 <div> <h1>html转化word</h1> <p>Enter/paste your document here:</p> <textarea id="content" cols="60" rows="10"> <p>We all live in a yellow submarine, yellow submarine, yellow submarine, yellow submarine</p> <p>Images can also be exported if you source them as base64 DATA URI.</p> <img src="cat.jpg" /> <img src="http://docs.asprain.cn/javatutorial/images/oracle-java-logo.png" /> </textarea> <div class="page-orientation"> <span>Page orientation:</span> <label><input type="radio" name="orientation" value="portrait" checked>Portrait</label> <label><input type="radio" name="orientation" value="landscape">Landscape</label></div> <button id="convert">Convert</button> <div id="download-area"></div> </div> // script <script src="./FileSave.js"></script> <script src="./html-docx.js"></script> // 逻辑 document.getElementById('convert').addEventListener('click', function(e) { e.preventDefault(); const content1 = document.getElementById('output').innerHTML; const content = document.getElementById('content').value; embedImage(content).then((content) => { var orientation = document.querySelector('.page-orientation input:checked').value; var blob = htmlDocx.asBlob(content, {orientation: orientation}); saveAs(blob, 'test.docx'); var link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'document.docx'; link.textContent='Click here if your download has not started automatically'; var downloadArea = document.getElementById('download-area'); downloadArea.innerHTML = ''; downloadArea.appendChild(link); }); }); /** * @desc 将图片嵌入HTML中 * @param {html} String * @return Promise(html) */ function embedImage(html){ if(typeof(html) !== 'string') return; let doc = new DOMParser().parseFromString(html, 'text/html'); debugger; let images = doc.images; //if(images.length==0)return '<!doctype html>'+doc.documentElement.outerHTML; return new Promise((resolve,reject)=>{ function _iterate(i){ if(i==images.length){ resolve('<!doctype html>'+doc.documentElement.outerHTML); return; // 终于 } let img=images[i]; let url=img.src; // 正在嵌入第i张图片 getBase64(url,function(base64){ if(base64==null){ img.remove(); _iterate(i); } else { img.src=base64; _iterate(++i); } }) } _iterate(0); }) } /** * @desc 从URL取得base64 * @param {url} String 网址 * @param {callback} Function 如果能打开图片,参数为打开图片的blob,如果不能打开图片,参数为null * @return void */ function getBase64(url,callback) { const xhr = new XMLHttpRequest(); xhr.responseType='blob' xhr.onload = () => { const blob=xhr.response; var reader = new FileReader(); reader.onload = function (e) { callback(reader.result); } reader.readAsDataURL(blob); }; xhr.onerror = (err) => { callback(null) }; xhr.open('GET', url, true); xhr.send(null); } |
设置样式
找到需要操作的dom元素,dom添加行内样式即可,注意:添加行内样式时,需要注意代码执行顺序,避免有些行内样式被覆盖。
项目中遇到问题:
1.util问题
参考:Module not found: Error: Can‘t resolve ‘path‘_can't resolve 'path-CSDN博客
2.表格样式问题
参考:JS word下载(含两种方式:html转word、模板转word) - 简书
3.html-docx-js的with函数问题
修改源码:
参考:JS word下载(含两种方式:html转word、模板转word) - 简书
插件推荐 | html文本转docx文档 - 简书