美文网首页
vue 把页面导出成PDF

vue 把页面导出成PDF

作者: 蜗牛的学习方法 | 来源:发表于2025-11-02 09:34 被阅读0次

使用html2canvas把页面导出成PDF

#toPdf.js
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";

/**
 * 导出为多页PDF(完整、清晰、不丢尾部内容)
 * @param {HTMLElement} element 要导出的DOM元素
 * @param {string} filename 导出的文件名
 */
export const exportPdf = async (element, filename = "导出报告.pdf") => {
  const A4_WIDTH = 595.28; // A4 宽度 pt
  const A4_HEIGHT = 841.89; // A4 高度 pt

  window.scrollTo(0, 0); // 确保完整渲染

  const canvas = await html2canvas(element, {
    scale: 2,
    useCORS: true,
    allowTaint: true,
    scrollX: 0,
    scrollY: 0,
    windowWidth: element.scrollWidth,
    windowHeight: element.scrollHeight,
  });

  const imgWidth = A4_WIDTH;
  const imgHeight = (canvas.height * imgWidth) / canvas.width;
  const pdf = new jsPDF("p", "pt", "a4");

  const pageCanvas = document.createElement("canvas");
  const pageCtx = pageCanvas.getContext("2d");

  // 每页在原始Canvas中对应的像素高度
  const pageHeightPx = (canvas.width * A4_HEIGHT) / A4_WIDTH;
  let remainingHeight = canvas.height;
  let pageIndex = 0;

  while (remainingHeight > 0) {
    const startY = pageIndex * pageHeightPx;
    const sliceHeight = Math.min(pageHeightPx, canvas.height - startY);

    // 创建一张临时画布绘制每页内容
    pageCanvas.width = canvas.width;
    pageCanvas.height = sliceHeight;

    // 从原canvas中截取该页区域
    pageCtx.clearRect(0, 0, canvas.width, sliceHeight);
    pageCtx.drawImage(canvas, 0, startY, canvas.width, sliceHeight, 0, 0, canvas.width, sliceHeight);

    // 转为图片
    const pageData = pageCanvas.toDataURL("image/jpeg", 1.0);

    // 添加到PDF
    if (pageIndex > 0) pdf.addPage();
    const pageImgHeight = (sliceHeight * imgWidth) / canvas.width;
    pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, pageImgHeight);

    remainingHeight -= sliceHeight;
    pageIndex++;
  }

  pdf.save(filename);
};

使用

 await exportPdf(this.$refs.reportContent,`测试.pdf`);

相关文章

网友评论

      本文标题:vue 把页面导出成PDF

      本文链接:https://www.haomeiwen.com/subject/bjvnxstx.html