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.最终效果

相关推荐
CodeCraft Studio11 分钟前
PDF处理控件Aspose.PDF教程:在C#中将PDF转换为Base64
服务器·pdf·c#·.net·aspose·aspose.pdf·pdf转base64
ღ_233339 分钟前
vue3二次封装element-plus表格,slot透传,动态slot。
前端·javascript·vue.js
xiaohe060140 分钟前
🔒 JavaScript 不是单线程吗?怎么还能上“锁”?!
javascript·github
摸着石头过河的石头43 分钟前
JavaScript继承的多种实现方式详解
前端·javascript
Ashley的成长之路1 小时前
NativeScript-Vue 开发指南:直接使用 Vue构建原生移动应用
前端·javascript·vue.js
朕的剑还未配妥1 小时前
Vue 2 响应式系统常见问题与解决方案(包含_demo以下划线开头命名的变量导致响应式丢失问题)
前端·vue.js
JNU freshman1 小时前
Element Plus组件
前端·vue.js·vue3
软件技术NINI2 小时前
MATLAB疑难诊疗:从调试到优化的全攻略
javascript·css·python·html
南风微微吹2 小时前
26考研英语一、二真题试卷及答案解析PDF电子版(1980-2025年)
考研·pdf
知识分享小能手2 小时前
uni-app 入门学习教程,从入门到精通,uni-app组件 —— 知识点详解与实战案例(4)
前端·javascript·学习·微信小程序·小程序·前端框架·uni-app