vue 把頁(yè)面導(dǎo)出成PDF

使用html2canvas把頁(yè)面導(dǎo)出成PDF

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

/**
 * 導(dǎo)出為多頁(yè)P(yáng)DF(完整、清晰、不丟尾部?jī)?nèi)容)
 * @param {HTMLElement} element 要導(dǎo)出的DOM元素
 * @param {string} filename 導(dǎo)出的文件名
 */
export const exportPdf = async (element, filename = "導(dǎo)出報(bào)告.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");

  // 每頁(yè)在原始Canvas中對(duì)應(yīng)的像素高度
  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);

    // 創(chuàng)建一張臨時(shí)畫布繪制每頁(yè)內(nèi)容
    pageCanvas.width = canvas.width;
    pageCanvas.height = sliceHeight;

    // 從原canvas中截取該頁(yè)區(qū)域
    pageCtx.clearRect(0, 0, canvas.width, sliceHeight);
    pageCtx.drawImage(canvas, 0, startY, canvas.width, sliceHeight, 0, 0, canvas.width, sliceHeight);

    // 轉(zhuǎn)為圖片
    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,`測(cè)試.pdf`);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容