前端界面生成PDF并导出下载

2023-04-26  本文已影响0人  一只小vivi

前端界面生成PDF并导出下载

通过 html2canvas 将 HTML 页面转换成图片,然后再通过 jspdf 将图片的 base64 生成为 pdf 文件

1.安装
npm install html2canvas --save 
npm install jspdf --save
2.代码展示
<template>
  <div class="down-load-pdf" id="downLoadPdf" style="width: 800px">
    <img src="@/assets/IMG2.jpg" alt="" />
    <div class="btn" @click="downLoadHandler">
      <span>点我去下载</span>
    </div>
  </div>
</template>

<script>
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
  name: "DownLoadPdf",
  data() {
    return {
      title: "我是测试代码",
    };
  },
  methods: {
    getPdf() {
      return new Promise((resolve) => {
        html2Canvas(document.querySelector("#downLoadPdf"), {
          allowTaint: false,
          useCORS: true, // allowTaint、useCORS只能够出现一个
          imageTimeout: 0,
          dpi: 300, // 像素
          scale: 4, // 图片大小
        }).then(function (canvas) {
          // 用于将canvas对象转换为base64位编码
          let pageData = canvas.toDataURL("image/jpeg", 1.0),
            canvasWidth = canvas.width,
            canvasHeight = canvas.height,
            concentWidth = 500,
            concentHeight = Math.round(
              (concentWidth / canvasWidth) * canvasHeight
            ),
            position = 72,
            pageHeight = 892,
            height = concentHeight;
          // 新建一个new JsPDF,A3的像素大小 842*1191,A4的像素大小 592*841。这个px像素不准确,不清楚他们的像素大小来源如何
          let PDF = new JsPDF("p", "px", "a3");
          if (height <= pageHeight) {
            // 添加图片
            PDF.addImage(
              pageData,
              "JPEG",
              68,
              position,
              concentWidth,
              concentHeight
            );
          } else {
            while (height > 0) {
              PDF.addImage(
                pageData,
                "JPEG",
                68,
                position,
                concentWidth,
                concentHeight
              );
              height -= pageHeight;
              position -= pageHeight;
              if (height > 0) {
                PDF.addPage();
              }
            }
          }
          // 保存 pdf 文档
          PDF.save(`${"我是测试代码"}.pdf`);
          resolve(true);
        });
      });
    },
    downLoadHandler() {
      this.getPdf();
    },
  },
};
</script>

<style scoped lang="scss">
img {
  width: 300px;
  height: 500px;
  margin-right: 20px;
}
.btn {
  text-align: center;
  font-size: 0;
  margin-top: 20px;
  span {
    font-size: 12px;
    padding: 5px 10px;
    border-radius: 8px;
    border: 1px solid #008c8c;
    cursor: pointer;
    display: inline-block;
    line-height: 1;
  }
}
</style>
3.页面展示效果
image.png
上一篇下一篇

猜你喜欢

热点阅读