预览在线的pdf

本案例借助了pdf.js实现的一个预览在线pdf的小案例,可选择跳转到指定页码。
ShowPDF接收三个参数:url:pdf在线地址,className:类名,page:跳转到的指定页码,默认是1。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div class="pdfDemo"></div>
  <img src="" alt="" srcset="">
</body>

</html>
 
<script src="https://cdn.bootcss.com/pdf.js/2.2.228/pdf.min.js"></script>

<script>
  class ShowPDF {
    constructor({ className, url, page = 1 }) {
      if (!url) throw new Error('url是必填项');
      if (!className) throw new Error('className是必填项');
      this.className = className;
      this.url = url;
      this.page = page;
      this.pdf = null;
    }
    async show() {
      const imageArr = await this.getImageArr(this.url)
      console.log(imageArr);
      const html = this.getImageHtml(imageArr);
      const pdfDemo = document.querySelector(this.className);
      pdfDemo.innerHTML = html;
      const viewImage = document.querySelectorAll(`${this.className} img`)[this.page - 1]
      setTimeout(() => {
        viewImage.scrollIntoView({
          behavior: "smooth", // 平滑过渡
          block: "start", // 居中
        });
      }, 1000)
    }
    getImageArr(url) {
      return new Promise((resolve, reject) => {
        let loadingTask = pdfjsLib.getDocument(url);
        loadingTask.promise.then(async (pdf) => {
          this.pdf = pdf;
          const numPages = pdf._pdfInfo.numPages;
          const imgArr = []
          for (let i = 1; i <= numPages; i++) {
            let imgUrl = await this.PdfToJpg(i)
            imgArr.push(imgUrl)
          }
          resolve(imgArr)
        });
      })
    }

    getImageHtml(imgArr) {
      let html = "";
      imgArr.forEach(item => html += ` <img src="${item}">`)
      return html
    }

    //pdf转jpg
    PdfToJpg(pageNum, callback) {
      return new Promise(async (resolve, reject) => {
        const page = await this.pdf.getPage(pageNum)
        let canvas = document.createElement("canvas");
        let context = canvas.getContext('2d');
        let scale = 1.5;
        let viewport = page.getViewport({ scale: scale });
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        let renderContext = {
          canvasContext: context,
          viewport: viewport
        };
        let renderTask = page.render(renderContext)
        renderTask.promise.then(function () {
          let imgUrl = canvas.toDataURL('image/jpeg'); //转换为base64
          resolve(imgUrl)
        })
      })
    }

  }

  new ShowPDF({
    url: "http://www.raomaiping.host/1.pdf",
    className: ".pdfDemo",
    page: 4
  }).show()
</script>
posted @ 2021-08-31 21:47  前端小菜鸟吖  阅读(213)  评论(0编辑  收藏  举报