移动端vue项目pdfjs使用

此案例使用的是vue2的@vue/composition-api,大部分代码来自 https://juejin.cn/post/6909252620741787656

此案例根据用户的屏幕宽度自适应为宽度100%

vue和pdfjs版本 

"vue": "^2.6.12",
"pdfjs-dist": "^2.7.570",

html

<div class='pdf-wrap'>
  <canvas
    v-for="page in pdfPages"
    :key="page"
    :id="'pdfCanvas' + page"
  ></canvas>
</div>

js

let PDFJS = require('pdfjs-dist')
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry.js')
export default{
  setup(){
    const pdfData = reactive({
      pdfPages: [], // 页数
      pdfWidth: "", // 宽度
      pdfSrc: "", // 地址
      pdfDoc: "", // 文档内容
      pdfScale: 1 // 放大倍数
    })
    onMounted(() => {
      let loadingTask = PDFJS.getDocument(pdfData.pdfSrc)
      loadingTask.promise.then(function(pdf) {
        pdfData.pdfDoc = pdf;
        pdfData.pdfPages = pdf.numPages;
        // this.$nextTick(() => {
        renderPage(1);
        // });
        function renderPage(num){
          pdfData.pdfDoc.getPage(num).then(page => {
            let canvas = document.getElementById("pdfCanvas" + num);
            let ctx = canvas.getContext("2d");
            let dpr = window.devicePixelRatio || 1;
            let bsr =
                ctx.webkitBackingStorePixelRatio ||
                ctx.mozBackingStorePixelRatio ||
                ctx.msBackingStorePixelRatio ||
                ctx.oBackingStorePixelRatio ||
                ctx.backingStorePixelRatio ||
                1;
            let ratio = dpr / bsr;
            let viewport =page.getViewport({ scale: pdfData.pdfScale });
            console.log('viewport',viewport)
            canvas.width = viewport.width  * ratio;
            canvas.height = viewport.height * ratio;
            canvas.style.width =window.innerWidth + "px";
            pdfData.pdfWidth = viewport.width + "px";
            canvas.style.height = window.innerWidth * viewport.height / viewport.width  + "px";
            ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
            // 将 PDF 页面渲染到 canvas 上下文中
            let renderContext = {
              canvasContext: ctx,
              viewport: viewport
            };
            page.render(renderContext);
            if (pdfData.pdfPages > num) {
              renderPage(num + 1);
            }
          });
        }
      }, function(err) {
        console.error(reason)
      })
    })
  }
}

代码不一定要放在onMounted中,只要保证renderPage函数调用时dom已经渲染就可以了。

使用require方式引用,是因为import方式可能找不到模块

上一篇:移动端的理解(2)


下一篇:cannot be read or is not a valid ZIP file