vue中PDF文件转图片方式

1、在vue中安装依赖  pdfjs-dist   

2、在需要引用的文件中添加

  import * as pdfjs from 'pdfjs-dist'
  import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
  pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker

3、编写需要转换的方法

<div v-for="(item, i) in imgFiles" :key="i" style="width:100vw;margin-top:10px;">
              <canvas :id="`pdf_canvas_${item}`" style="border: 1px solid #eeeeee;float:left;"></canvas>
          </div>
      // 地址转文件   url为需要转化的文件路径
      getFileFromUrl(url) {
        const that = this;
        fetch(url)
        .then((response) => response.blob()) // 返回Blob对象表示文件内容
        .then((blob) => {
            const file = new File([blob], 'filename.pdf'); // 创建File对象并指定文件名
            // 处理文件逻辑...
            console.log('已成功将URL转换为文件!', file);
            that.handlePdf(file)
        })
        .catch((error) => {
            console.error('转换失败:', error);
        });
      },
      handlePdf(file) {
            let that = this;
            var reader = new FileReader();
            reader.readAsDataURL(file); //将文件读取为 DataURL
            reader.onload = function () { //文件读取成功完成时触发
                const loadingTask = pdfjs.getDocument(reader.result)
                loadingTask.promise.then((pdf) => {
                    var pageNum = pdf.numPages;
                    console.log("页数:" + pageNum);
                    //准备图片
                    for (let i = 1; i <= pageNum; i++) {
                        let one = i;
                        that.imgFiles.push(one);
                    }
                    //处理
                    for (let i = 1; i <= pageNum; i++) {
                        pdf.getPage(i).then((page) => {
                            const canvas = document.getElementById('pdf_canvas_' + i);
                            const ctx = canvas.getContext('2d')
                            const viewport = page.getViewport({ scale: 1 })
                            canvas.height = viewport.height;
                            canvas.width = viewport.width;
                            const destWidth = viewport.width/1.5;
                            canvas.style.width = destWidth + 'px';
                            canvas.style.height = destWidth * (viewport.height / viewport.width) + 'px';
                            page.render({
                                canvasContext: ctx,
                                viewport,
                            })
                        })
                    }
                })
            }
        },

 

posted @ 2024-03-05 17:37  zhumeng_WEB  阅读(1546)  评论(0编辑  收藏  举报