Vue中html导出docx、pdf文件

1.npm安装

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

2.引入

import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';

3.导出

import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
import axios from 'axios'
export const downloadWord = {
  data() {
    return {

    }
  },
  methods: {
    //type有pdf和docx类型
    async downloadWord(id, result, type) {
       //自定义
      const cssStyle = `
          <style>
            body{
            font-size: 16px;
          }
          .red{
            color: blue;
          }
          .divCenter{
            text-align: center;
            font-size: 25px;
            font-weight: bold;
          }
          .mb20{
            margin-bottom: 20px;
          }
          </style>`

      const loading = this.$loading({
        lock: true,
        customClass: "create-isLoading",
        text: "正在下载,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0)"
      });
        let content = `
        <div class="divCenter" >${result.title}</div>
        <div class="mb20">${result.htmlContent.replace(/ /g, '&nbsp;&nbsp;')}</div>
        </div>`
        const articleContent =
          `<!DOCTYPE html><html><head><meta charset="UTF-8">${cssStyle}</head><body>${content}</body></html>`
        const blob = htmlDocx.asBlob(articleContent);
        const file = await new File([blob], result.title + "." + type, {
          lastModified: Date.now()
        });
        let fileName = result.title + "." + type;
        let formData = new FormData()
        formData.append('file', file)
        formData.append('id', id)
        formData.append('convertType', type)
        const config = {
          headers: {
            "Content-Type": "multipart/form-data;"
          },
          responseType: "blob"
        };
        const res = await axios.post(this.$prefix + "/api/v2/file/convert", formData, config)
        if (res.status === 200) {
          const blob = new Blob([res.data], { type: "octet-stream" });
          saveAs(blob, fileName);
        }
      loading.close();
    },
  },
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值