首页 前端知识 vue使用html-docx-js 实现 html内容转word下载

vue使用html-docx-js 实现 html内容转word下载

2024-08-07 00:08:09 前端知识 前端哥 206 148 我要收藏

借鉴的是点击这里这篇,我自己引入之后有些报错和问题,修改了一下。

npm install html-docx-js
npm install file-saver

<!-- 包容要转为word的html盒子 -->
<div class="export-box">
    <!-- 插入html的内容 -->
</div>
<button @click="gohtml"></button>
<script setup lang="ts">
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';

// html转为word
const gohtml = () => {
    //.export-box 需要转word的最大dom盒子的类名
    const app = document.querySelector('.export-box');
    const cloneApp = app.cloneNode(true);
    const canvases = app.getElementsByTagName('canvas');
    const cloneCanvases = cloneApp.getElementsByTagName('canvas');

    const promises = Array.from(canvases).map((ca, index) => {
        return new Promise((res) => {
            const url = ca.toDataURL('image/png', 1);
            const img = new Image();
            img.onload = () => {
                URL.revokeObjectURL(url);
                res();
            };
            img.src = url;
            // 生成img插入clone的dom的canvas之前
            cloneCanvases[index].parentNode.insertBefore(
                img,
                cloneCanvases[index],
            );
        });
    });
    // 移除原来的canvas
    const cloneCanvas = cloneApp.getElementsByTagName('canvas');
    Array.from(cloneCanvas).forEach((ca) => ca.parentNode.removeChild(ca));

    Promise.all(promises).then(() => {
        convertImagesToBase64(cloneApp);
        console.log(document.head.outerHTML);
        const converted = htmlDocx.asBlob(`
      <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><style>
      ${document.head.outerHTML}
      </head>
      <body>
      ${cloneApp.outerHTML}
      </body>
      </html>`);
        saveAs(converted, 'test.docx');
    });
};

const convertImagesToBase64 = (cloneApp) => {
    let regularImages = cloneApp.getElementsByTagName('img');
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    
    for (let index = 0; index < regularImages.length; index++) {
        canvas.width = regularImages[index].width;
        canvas.height = regularImages[index].height;
        ctx.drawImage(
            regularImages[index],
            0,
            0,
            regularImages[index].width,
            regularImages[index].height,
        );
        let ext = regularImages[index].src
            .substring(regularImages[index].src.lastIndexOf('.') + 1)
            .toLowerCase();
        let dataURL = canvas.toDataURL('image/' + ext);
        regularImages[index].setAttribute('src', dataURL);
    }
    canvas.remove();
};
</script>

import htmlDocx from 'html-docx-js/dist/html-docx';

一开始引入html-docx-js时,会报node_modules里一个with(obj)的错,把with()语句和花括号删除掉,再把里面的变量加上obj. 就可以了。如下

with(obj){
__p += '------=mhtDocumentPart\nContent-Type: ' +
((__t = ( contentType )) == null ? '' : __t) +
'\nContent-Transfer-Encoding: ' +
((__t = ( contentEncoding )) == null ? '' : __t) +
'\nContent-Location: ' +
((__t = ( contentLocation )) == null ? '' : __t) +
'\n\n' +
((__t = (encodedContent )) == null ? '' : __t) +
'\n';
}

//改为

__p += '------=mhtDocumentPart\nContent-Type: ' +
((__t = ( obj.contentType )) == null ? '' : __t) +
'\nContent-Transfer-Encoding: ' +
((__t = ( obj.contentEncoding )) == null ? '' : __t) +
'\nContent-Location: ' +
((__t = ( obj.contentLocation )) == null ? '' : __t) +
'\n\n' +
((__t = ( obj.encodedContent )) == null ? '' : __t) +
'\n';

.export-box div里 也可以放echarts图表

转载请注明出处或者链接地址:https://www.qianduange.cn//article/14926.html
标签
评论
发布的文章

前端-axios应用在html文件

2024-08-15 23:08:39

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!