vue3 antd modal对话框里的前端html导出成pdf并下载

发布于:2025-07-25 ⋅ 阅读:(16) ⋅ 点赞:(0)

1.安装html2canvas和jspdf:

npm install html2canvas jspdf

2.新建exportToPDF.ts

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

const exportToPDF = async (element, filename = 'export.pdf')  => {
  const pdf = new jsPDF('p', 'mm', 'a4');
  const pageHeight = pdf.internal.pageSize.getHeight();  // A4高度(841.89mm)
  const pageWidth = pdf.internal.pageSize.getWidth();    // A4宽度(210mm)
  // const pixelsPerMM = 3.78; // 像素与毫米转换系数(96dpi)
   const pixelsPerMM = 5.5
 
  // 获取DOM实际高度
  const contentHeight = element.scrollHeight; 
  // 计算总页数 
  const totalPages = Math.ceil(contentHeight  / (pageHeight * pixelsPerMM)); // 3.8为像素-mm转换系数 
 
  let position = 0;
  for (let i = 0; i < totalPages; i++) {
    // 分段渲染Canvas 
    const canvas = await html2canvas(element, {
      scale: 2,
      y: position,              // 起始位置 
      height: pageHeight * pixelsPerMM, // 当前页高度 
      useCORS: true 
    });
 
    const imgData = canvas.toDataURL('image/jpeg',  0.92);
    const imgWidth = pageWidth - 20; // 留页边距 
    const imgHeight = (canvas.height  * imgWidth) / canvas.width; 
 
    // 添加新页(首页除外)
    if (i > 0) pdf.addPage();  
    
    pdf.addImage(imgData,  'JPEG', 10, 10, imgWidth, imgHeight);
    position += pageHeight * pixelsPerMM; // 更新截取位置
  }
  pdf.save(filename); 

}

export { exportToPDF }

pixelsPerMM这个值可以自行调节

3.在DownloadReport.vue内使用:


<script lang='ts' setup>   
<a-modal 
    v-model:visible="status.visible" 
    title="企业报告" 
    centered 
    :forceRender="true"
    style="width:1200px">
    <div class="tools">
      <a-button type="primary" @click="exportPDF">
        报告导出
      </a-button>
    </div>
    <div ref="pdfRef" id="content-to-pdf">
        // 报告内容
    </div>
   </a-modal>      
    
    import { exportToPDF } from "@/utils/exportToPDF"
    
    // 报告导出
const exportPDF = async () => {
  const element = document.getElementById('content-to-pdf');
  exportToPDF(element, 'report.pdf'); 
}
</script>

需要注意的是,如果报告内容里有外链形式的图片,最好让后端同时进行转发或加个获取图片base64的接口,否则会报跨域问题,导致图片无法生成


网站公告

今日签到

点亮在社区的每一天
去签到