在vue项目中将数据导出为pdf

这里我使用的是插件来完成的

首先安装插件

npm i jsPDF html2canvas
或
yarn add jsPDF html2canvas

在需要使用的地方引入

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

定义一个导出方法

 导出


const exportDataToPDF=()=> {
      // 获取要导出为PDF的元素(此处假设我们要导出整个页面)
      const element = document.getElementById('app')
      // 使用html2canvas将元素转换为canvas对象
      html2canvas(element).then((canvas) => {
        const imageData = canvas.toDataURL('image/png');
        // 创建PDF实例
        const pdf = new jsPDF();
        const imgProps = pdf.getImageProperties(imageData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        
        // 将canvas画布作为图像添加到PDF
        pdf.addImage(imageData, 'PNG', 0, 0, pdfWidth, pdfHeight);
            
        // 导出PDF文件
        pdf.save('data.pdf');
      });
    }

这是完整代码


有任何问题请私信。

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