前端将页面内容生成Word文件并下载
根据产品需求,需要将页面内容下载成可编辑的Word文件
1.插件依赖
// 注意:file-saver 依赖 Blob 对象 import { saveAs } from 'file-saver'; // htmlDocx 的作用就是将html字符串转成Blob对象 import htmlDocx from 'html-docx-js/dist/html-docx';
2.生成Word文件并下载至本地
/** * 1.导出局部的html页面 * @param {} dom 局部的html页面 * @param {*} fileName 导出文件的名称 * @param {*} title */ export const exportDocx = (dom, fileName, config, { title = document.title, width } = {}) => { if (!dom) return; config = config || {}; let copyDom = document.createElement('span'); const titleDom = document.createElement('title'); titleDom.innerText = title; copyDom.appendChild(titleDom); const cloneDom = dom.cloneNode(true); if (width) { const domTables = cloneDom.getElementsByTagName('table'); if (domTables.length) { for (const table of domTables) { table.style.width = width + 'px'; } } } copyDom.appendChild(cloneDom); const htmlTemp = copyDom.innerHTML; copyDom = null; const iframeDom = document.createElement('iframe'); const attrObj = { height: 0, width: 0, border: 0, wmode: 'Opaque', }; const styleObj = { position: 'absolute', top: '-999px', left: '-999px', }; Object.entries(attrObj).forEach(([key, value]) => { iframeDom.setAttribute(key, value); }); Object.entries(styleObj).forEach(([key, value]) => { iframeDom.style[key] = value; }); document.body.insertBefore(iframeDom, document.body.children[0]); const iframeWin = iframeDom.contentWindow; // 1.获取iframe中的window const iframeDocs = iframeWin.document; // 2.获取iframe中的document iframeDocs.write(`<!doctype html>`); iframeDocs.write(htmlTemp); const htmlStyle = ` table{ table-layout: fixed; } td{ word-wrap: break-word; } `; const htmlDocContent = `<!DOCTYPE html><html><head><meta charset="UTF-8"><style></style></head><body style="text-indent:30px">${iframeDocs.documentElement.innerHTML}</body></html>`; var converted = htmlDocx.asBlob(htmlDocContent, config); saveAs(converted, fileName + '.docx'); document.body.removeChild(iframeDom); };
<div id="downloadWord"> <div>word 需要下载的内容</div> <div>word 需要下载的内容</div> <div>word 需要下载的内容</div> </div> <Button onClick={() => {
exportDocx(document.querySelector('#downloadWord'), 'docxName', {
margins: { left: 300, right: 300, top: 300, bottom: 150 },
});
>下载</Button>
注:通过此方法下载的 Word文件 在不编辑Word和另存为新Word文件情况下,无法通过获取Word格式获取文件内容