Vue2.0 通过vue-pdf-signature@4.2.7和pdfjs-dist@2.5.207实现PDF预览

1.安装依赖

javascript 复制代码
npm install pdfjs-dist@2.5.207 --save
javascript 复制代码
npm install vue-pdf-signature@4.2.7 --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.最终效果

相关推荐
yqcoder25 分钟前
reactflow 中 useNodesState 模块作用
开发语言·前端·javascript
会发光的猪。1 小时前
css使用弹性盒,让每个子元素平均等分父元素的4/1大小
前端·javascript·vue.js
天下代码客1 小时前
【vue】vue中.sync修饰符如何使用--详细代码对比
前端·javascript·vue.js
周全全2 小时前
Spring Boot + Vue 基于 RSA 的用户身份认证加密机制实现
java·vue.js·spring boot·安全·php
Domain-zhuo2 小时前
什么是JavaScript原型链?
开发语言·前端·javascript·jvm·ecmascript·原型模式
小丁爱养花2 小时前
前端三剑客(三):JavaScript
开发语言·前端·javascript
ZwaterZ2 小时前
vue el-table表格点击某行触发事件&&操作栏点击和row-click冲突问题
前端·vue.js·elementui·c#·vue
码农六六2 小时前
vue3封装Element Plus table表格组件
javascript·vue.js·elementui
徐同保2 小时前
el-table 多选改成单选
javascript·vue.js·elementui
快乐小土豆~~2 小时前
el-input绑定点击回车事件意外触发页面刷新
javascript·vue.js·elementui