Vue2.0 通过[email protected][email protected]实现PDF预览

1.安装依赖

javascript 复制代码
npm install [email protected] --save
javascript 复制代码
npm install [email protected] --save

2.在.vue文件中 script 部分引入

javascript 复制代码
<script>
import * as PDFJS from 'pdfjs-dist'
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.js');//解决pdf.js中文乱码问题
import pdf from 'vue-pdf-signature'
// 中文PDF加载空白引入依赖
import CMapReaderFactory from 'vue-pdf-signature/src/CMapReaderFactory'

export default {
 components: {pdf},
 data(){
	return{
	 		pdfPages: 0,//pdf页数
            pdfDoc: null,//pdf对象
		}
	},
	mounted() {
        this.getFileData();
    },
	methods:{
		//获取后台返回的文件流
		 getFileData() {
            this.$http.post("/doc/docarchivemanagereceive/preview", {
                ...this.from,
            }, {
                responseType: 'blob',
            }).then(({data: res}) => {
                 //pdf-main 滚动条回到顶部
                        this.$nextTick(() => {
                            document.getElementsByClassName('pdf-main')[0].scrollTop = 0
                        })

                        const blob = new Blob([res], {type: 'application/pdf'})
                        let fileUrl = URL.createObjectURL(blob)
                        this.loadFile(fileUrl)
            })
        },
         //加载pdf文件
        loadFile(url) {
            const loadingTask = pdf.createLoadingTask({
                url: url,
                cMapPacked: true,
                CMapReaderFactory
            });
            loadingTask.promise.then((pdf) => {
                this.pdfDoc = pdf;
                this.pdfPages = pdf.numPages;

              
                this.$nextTick(() => {
                    for (let i = 0; i < this.pdfPages; i++) {
                        this.renderPage(i + 1, i) // 从第一页开始渲染
                    }
                })
            }).catch((err) => {
                console.error("pdf 加载失败", err);
                this.$message.error("PDF文件打开失败");
               
            });
        },
        //获取分辨率
        getDeviceDPI() {
            var dpi = 96; // 默认值 96dpi

            if (window.screen && window.screen.deviceXDPI && window.screen.logicalXDPI) {
                dpi = window.screen.deviceXDPI / window.screen.logicalXDPI * dpi;
            } else if (window.devicePixelRatio) {
                dpi = dpi * window.devicePixelRatio;
            }

            return dpi;
        },
        //渲染pdf页
        renderPage(num, index, scale = 1.5, rotation = 0) {
            let deviceDPI = this.getDeviceDPI();
            this.pdfDoc.getPage(num).then((page) => {
                var viewport = page.getViewport({
                    scale: scale,
                    rotation: page.getViewport({scale: scale}).rotation + rotation
                });
                // Support HiDPI-screens.
                var outputScale = window.devicePixelRatio || 1;

                var canvas = document.getElementById('pdfCanvas' + index);
                var context = canvas.getContext('2d');

                canvas.width = Math.floor(viewport.width * outputScale);
                canvas.height = Math.floor(viewport.height * outputScale);
                canvas.style.width = Math.floor(viewport.width) + "px";
                canvas.style.height = Math.floor(viewport.height) + "px";

                canvas.parentNode.style.width = canvas.width + 'px';
                canvas.parentNode.style.height = canvas.height + 'px';

                var transform = outputScale !== 1
                    ? [outputScale, 0, 0, outputScale, 0, 0]
                    : null;

                var renderContext = {
                    canvasContext: context,
                    transform: transform,
                    viewport: viewport
                };
                page.render(renderContext);


            })
            //pdfjs-dist 2.0.945版本getViewport(scale)的传参方式
            /* this.pdfDoc.getPage(num).then((page) => {
                 var scale = 816 / page.getViewport(1).width * (window.devicePixelRatio || 1);
                 var scaledViewport = page.getViewport(scale);
                 var canvas = document.getElementById('pdfCanvas' + index);
                 var context = canvas.getContext('2d');
                 canvas.width = scaledViewport.width;
                 canvas.height = scaledViewport.height;
                 var renderContext = {
                     canvasContext: context,
                     viewport: scaledViewport
                 };
                 page.render(renderContext);

             })*/

        },
        
	}
	
}





</script>

3.在.vue文件中 html 部分引入

html 复制代码
<!--pdf文件预览-->
 <div class="pdf_view" >
      <div class="pdf-main">       
  		<div class="pdf_item" v-for="(item,index) in pdfPages" :key="index">
             <canvas :id="'pdfCanvas' + index"/>
        </div>
     </div>
 </div>

4.在.vue文件中 css 部分引入

css 复制代码
.pdf_view {
    height: calc(100vh - 116px);
    overflow: hidden;
    background: #F2F4F7;

}

.pdf-main {
    width: 100%;
    height: calc(100vh - 116px);
    overflow: auto;
    padding: 20px 0 0 20px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .pdf_item {
        position: relative;
        margin: 0 auto 20px;
    }
}

5.最终效果

相关推荐
拉不动的猪3 小时前
刷刷题50(常见的js数据通信与渲染问题)
前端·javascript·面试
拉不动的猪3 小时前
JS多线程Webworks中的几种实战场景演示
前端·javascript·面试
uhakadotcom4 小时前
Astro 框架:快速构建内容驱动型网站的利器
前端·javascript·面试
uhakadotcom4 小时前
了解Nest.js和Next.js:如何选择合适的框架
前端·javascript·面试
uhakadotcom4 小时前
Remix 框架:性能与易用性的完美结合
前端·javascript·面试
uhakadotcom4 小时前
Node.js 包管理器:npm vs pnpm
前端·javascript·面试
咖啡教室5 小时前
前端开发日常工作每日记录笔记(2019至2024合集)
前端·javascript
咖啡教室6 小时前
前端开发中JavaScript、HTML、CSS常见避坑问题
前端·javascript·css
市民中心的蟋蟀8 小时前
第五章 使用Context和订阅来共享组件状态
前端·javascript·react.js
逆袭的小黄鸭8 小时前
JavaScript 闭包:强大特性背后的概念、应用与内存考量
前端·javascript·面试