vue3使用jsPDF实现上传图片转pdf(可多图转多页pdf)

一、安装jsPDF

npm install jspdf

二、引入并使用,以下为完整示例代码

<template>
  <div>
    <span class="header_text">上传图片转pdf</span>
    <input
      type="file"
      @change="pdfUpload($event)"
      multiple
      accept="image/jpeg,image/jpg,image/png"
    />
  </div>
</template>

<script lang="ts" setup>
import { jsPDF } from "jspdf";
import { ref } from "vue";

const pdfList: any = ref([]);
//获取图片宽高
const getImgWidthHeight = (src: any) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    // 图片是否有缓存 如果有缓存可以直接拿 如果没有缓存 需要从onload拿
    if (img.complete) {
      const { width, height } = img;
      resolve({
        width,
        height,
      });
    } else {
      img.onload = function () {
        const { width, height } = img;
        resolve({
          width,
          height,
        });
      };
    }
  });
};

const pdfUpload = async (ev: any) => {
  let imgList = ev.target.files;
  const pdf = new jsPDF("p", "mm", "a4");
  for (let i = 0; i < imgList.length; i++) {
    // 仅限图片可操作
    if (["image/jpeg", "image/png"].includes(imgList[i].type)) {
      let url = URL.createObjectURL(imgList[i]);
      const { width, height } = await getImgWidthHeight(url);
      // A4页面宽高
      // const max = { width: 210, height: 300 };
      // 如果宽度>高度,宽度设置为160,高度缩放,反之则高度设置200,宽度缩放
      let finalWidth = 0;
      let finalHeight = 0;
      if (width > height) {
        finalWidth = 160;
        finalHeight = (160 / width) * height;
      } else {
        finalHeight = 200;
        finalWidth = (200 / height) * width;
      }
      // 在pdf中添加图片
      pdf.addImage(url, "png", 1, 1, finalWidth, finalHeight);
      // 有多个图片则添加多个pdf页面
      if (i !== imgList.length - 1) {
        pdf.addPage();
      }
    }
  }
  let blob = new Blob([pdf.output("blob")], { type: "application/pdf" });
  // pdf.output("datauristring")会导出base64
  // let pdfBase64 = pdf.output("datauristring");

  //文件名自定义,可以拼接时间戳保证唯一性
  let name = "pdfFile";
  // 生成file文件
  let file = new File([blob], `${name}.pdf`, { type: blob.type });
  // 将文件push到文件list中待用
  pdfList.value.push(file);
};
</script>

<style lang="scss" scoped>
</style>

三、实现效果

四、写在最后

实现图片转pdf主要还是在于对jsPDF中addImage()addPage()以及output()方法的使用,当然jsPDF的功能不止于此,想了解更多可以点击链接进入官网(https://github.com/parallax/jsPDF

如果觉得以上内容对你有所帮助的话,就帮博主点赞收藏吧~~

猜你喜欢

转载自blog.csdn.net/Sylvasylva/article/details/134336351
今日推荐