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 = `
          `

      const loading = this.$loading({
        lock: true,
        customClass: "create-isLoading",
        text: "正在下载,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0)"
      });
        let content = `
        
${result.title}
${result.htmlContent.replace(/ /g, '  ')}
` const articleContent = `${cssStyle}${content}` 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(); }, }, }

你可能感兴趣的:(vue.js,pdf,javascript)