前端dom元素导出成为图片或者pdf小案例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Export Element to Image with html2canvas</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.2/html2canvas.min.js"></script>
  </head>
  <body>
    <div class="aa">
      <div>导出图片</div>
      <!-- 确保 src 属性指向的图片是可访问的 -->
      <img id="myImage" src="./baidu.png" alt="" />
    </div>
    <button id="captureButton">导出为图片</button>

    <script>
      document.addEventListener("DOMContentLoaded", function () {
        var captureButton = document.getElementById("captureButton");
        var myImage = document.getElementById("myImage");

        // 检查图片是否加载完成,如果加载完成则立即执行回调函数
        var imageLoaded = new Promise((resolve) => {
          if (myImage.complete) {
            resolve();
          } else {
            myImage.addEventListener("load", () => resolve());
          }
        });

        captureButton.addEventListener("click", async function () {
          await imageLoaded; // 等待图片加载完成

          var element = document.querySelector(".aa");

          html2canvas(element).then(function (canvas) {
            var imageData = canvas.toDataURL("image/png");

            var link = document.createElement("a");
            link.download = "exported-image.png";
            link.href = imageData;
            link.click();
          });
        });
      });
    </script>
  </body>
</html>

pdf 比较少的情况

import jsPDF from "jspdf";
import html2Canvas from "html2canvas";
    getPrimaryPDF2() {
      // 获取 DOM 元素
      const element = document.getElementById("pdf_dom2");

      // 确保元素是可见的,可能需要调整其 position 属性为 relative
      element.style.position = "relative";
      element.style.overflow = "hidden";

      // 使用 html2Canvas 将 DOM 元素转换为 Canvas
      html2Canvas(element, {
        useCORS: true,
        scale: 2
      }).then(canvas => {
        // 创建 jsPDF 实例
        const pdf = new jsPDF({
          orientation: "p", // 纵向
          unit: "pt", // 使用 'pt' 作为单位
          format: "a4" // A4 纸张大小
        });

        // 计算图片的宽度和高度
        const imgWidth = 210 * 2.834; // A4 宽度转换为 pt
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        const totalPages = Math.ceil(imgHeight / (297 * 2.834));
        // 将 Canvas 转换为图片并添加到 PDF
        const imgData = canvas.toDataURL("image/png");

        for (let i = 0; i < totalPages; i++) {
          if (i > 0) {
            pdf.addPage();
          }

          const offsetY = i * (297 * 2.834);

          pdf.addImage(imgData, "JPEG", 0, -offsetY, imgWidth, imgHeight);
        }

        if (this.pdfAll.title) {
          pdf.save(
            this.pdfAll.title + "-" + this.pdfAll.arrImg.length + ".pdf"
          );
        } else {
          const date = Number(Date.now());
          pdf.save(date + "-canvas.pdf");
        }
      });
    },

pdf多交多的情况

  getPrimaryPDF2() {
      let _this = this;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      try {
        // 存储PDF文件的数组
        const pdfPromises = [];
        // 获取 DOM 元素
        const elementArr = document.getElementsByClassName("pdf_box2");

        for (let index = 0; index < elementArr.length; index++) {
          const element = elementArr[index];
          // 使用 html2Canvas 将 DOM 元素转换为 Canvas
          pdfPromises.push(
            new Promise((resolve, reject) => {
              html2Canvas(element, {
                useCORS: true,
                scale: 3
              }).then(canvas => {
                // 创建 jsPDF 实例
                const pdf = new jsPDF({
                  orientation: "p", // 纵向
                  unit: "pt", // 使用 'pt' 作为单位
                  format: "a4" // A4 纸张大小
                });

                // 计算图片的宽度和高度
                const imgWidth = 210 * 2.834; // A4 宽度转换为 pt
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                const totalPages = Math.ceil(imgHeight / (297 * 2.834));
                // 将 Canvas 转换为图片并添加到 PDF
                const imgData = canvas.toDataURL("image/png");

                for (let i = 0; i < totalPages; i++) {
                  if (i > 0) {
                    pdf.addPage();
                  }

                  const offsetY = i * (297 * 2.834);

                  pdf.addImage(
                    imgData,
                    "PNG",
                    0,
                    -offsetY,
                    imgWidth,
                    imgHeight
                  );
                }
                resolve(pdf.output("blob"));
              });
            })
          );
        }

        // 等待所有PDF生成
        Promise.all(pdfPromises)
          .then(pdfBlobs => {
            // 使用JSZip创建ZIP文件
            const zip = new JSZip();
            pdfBlobs.forEach((blob, index) => {
              const fileName = `pdf_page_${index + 1}.pdf`;
              zip.file(fileName, blob);
            });

            let fileNameDown = "";
            if (_this.pdfAll.title) {
              fileNameDown =
                _this.pdfAll.title + "-" + _this.pdfAll.arrImg.length;
            } else {
              const date = Number(Date.now());
              fileNameDown = date + "-canvas";
            }

            // 生成ZIP文件并下载
            zip.generateAsync({ type: "blob" }).then(content => {
              saveAs(content, fileNameDown + ".zip");
              loading.close();
            });
          })
          .catch(error => {
            console.error("Error generating PDFs: ", error);
            loading.close();
          });
      } catch (error) {
        loading.close();
      }
    },

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值