当前位置:首页 > VUE

vue实现导出PDF

2026-02-19 04:52:40VUE

实现Vue导出PDF的方法

使用html2canvas和jspdf库

安装依赖库:

npm install html2canvas jspdf --save

在Vue组件中引入:

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

创建导出方法:

methods: {
  exportToPDF() {
    const element = document.getElementById('pdf-content');
    html2canvas(element).then(canvas => {
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 210;
      const pageHeight = 295;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      pdf.save('document.pdf');
    });
  }
}

使用vue-html2pdf插件

安装插件:

npm install vue-html2pdf --save

在组件中使用:

import VueHtml2pdf from 'vue-html2pdf'

export default {
  components: {
    VueHtml2pdf
  },
  methods: {
    generateReport() {
      this.$refs.html2Pdf.generatePdf()
    }
  }
}

模板部分:

<vue-html2pdf
  ref="html2Pdf"
  :html-to-pdf-options="options"
  filename="my-pdf"
  :paginate-x="156"
  :paginate-y="180"
>
  <div slot="pdf-content">
    <!-- 要导出的内容 -->
  </div>
</vue-html2pdf>
<button @click="generateReport">导出PDF</button>

使用pdfmake客户端生成

安装pdfmake:

npm install pdfmake --save

实现代码:

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

methods: {
  generatePDF() {
    const docDefinition = {
      content: [
        { text: 'PDF标题', style: 'header' },
        '这是PDF内容...',
        { text: '动态内容', margin: [0, 20, 0, 0] }
      ],
      styles: {
        header: {
          fontSize: 18,
          bold: true
        }
      }
    };
    pdfMake.createPdf(docDefinition).download('custom.pdf');
  }
}

注意事项

确保要导出的内容已完全渲染,可在mounted钩子或使用$nextTick处理异步渲染问题

对于大量数据或复杂布局,考虑分页处理避免PDF文件过大

中文支持需要额外配置字体,pdfmake需要注册中文字体

浏览器安全策略可能限制跨域资源导出,确保所有资源同源或已正确处理CORS

vue实现导出PDF

标签: vuePDF
分享给朋友:

相关文章

vue实现检测数组

vue实现检测数组

Vue 中检测数组变化的方法 Vue 的响应式系统无法直接检测到数组的某些变化,因为 JavaScript 的限制。以下是一些解决方案: 使用 Vue.set 或 this.$set Vue 提供…

vue卖座网实现

vue卖座网实现

Vue 卖座网实现 项目结构搭建 使用 Vue CLI 快速初始化项目,安装必要依赖如 Vue Router、Vuex、Axios。 创建核心目录结构:components(通用组件)、views(页…

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成…

vue实现后退

vue实现后退

Vue 实现后退功能的方法 在 Vue 中实现后退功能通常可以通过以下几种方式完成,具体取决于应用场景和需求。 使用 window.history API 通过原生 JavaScript 的 win…

vue实现app

vue实现app

Vue 实现 App 的常见方法 使用 Vue 开发移动端 App 主要有两种主流方案:混合开发(Hybrid)和原生渲染。以下是具体实现方式和工具链: 混合开发方案(WebView 嵌入) 通…

vue 动画 实现

vue 动画 实现

vue 动画实现方法 Vue 提供了多种方式实现动画效果,主要包括过渡动画和动态动画两类。 使用 <transition> 组件实现基础过渡 通过 Vue 内置的 <transit…