vue-pdf-embed预览PDF

时间:2025-05-14 11:49:02

一、vue-pdf-embed

链接:Yarn

1、安装插件

npm install vue-pdf-embed

2、文件中引入(分页效果已实现,样式请自行修改)

<template>
	<div class="download-pdf-preview" style="height: 450px; border:10px solid #D4D4D7;overflow: hidden; overflow-y: scroll">
		<!-- <vue-pdf-app style="height: 430px;" :pdf="pdfURL"></vue-pdf-app> -->
		<vue-pdf-embed ref="morePDF" :source="pdfURL" :page="currentPage" ></vue-pdf-embed>
	    <div class="ins-pdf-button-box">
			<span @click.stop="prePage">上一页</span>
			<span>{{currentPage}}/{{pages}}</span>
			<span @click.stop="nextPage">下一页</span>
		</div>
    </div>
	<div style="text-align: right; margin-top: 10px;">
		<Button type="text" v-if="back" style="color: #FF7D48; width: 100px;" @click="handleBack()">返回列表</Button>
		<Button style="color: #FF7D48; width: 100px; border-color: #FF7D48;" @click="handleDownload()">下载</Button>
	</div>
</template>

<script>
import {downloadBlob,base64ToBlob,blobToUrl} from '@/utils/index.js'
import VuePdfEmbed from "vue-pdf-embed"

export default {
	components: {
		VuePdfEmbed
	},
	emits : ['on-back'],
	props : {
		info : {
			type : Object,
			default : {}
		},
		back : {
            type:Boolean,
            default : false
        }
	},
	data(){
		return {	
	       pdfURL : ''	,//PDF URL
		   pages: [],
           numPages : 0,		//分页
		   currentPage : 1, //当前显示页数
		}
	},
	computed : {
		
	},
	watch: {
		info : {
			handler(data) {
				if(data?.base64Str){
					const blob = base64ToBlob(data.base64Str);  
	                this.pdfURL= blobToUrl(blob)
				}
			},
			deep: true,
			immediate: true
        }
	},
	methods : {
		//返回列表
		handleBack(){
			this.$emit('on-back')
		},
		//下载
		handleDownload(){
			downloadBlob(this.pdfURL,this.info.fileName)
		},
		async getPDFnums(url) {
			const page = await VuePdfEmbed.getDocument(url).promise
            this.pages = page.numPages
			this.currentPage = 1
		},
        // 上一页
		prePage() {
			var page = this.currentPage
			page = page > 1 ? page - 1 : this.numPages
			this.currentPage = page
		},

		// 下一页
		nextPage() {
			var page = this.currentPage
			page = page < this.numPages ? page + 1 : 1
			this.currentPage = page
		}
	},
	created(){
	},
	mounted () {
	}
}	
</script>

<style>
</style>

3、插件支持PDF地址,base64或二进制数据需要生成PDF地址

// PDF base64 转地址
export function base64ToBlob(base64Data){
    const binary = atob(base64Data);  
    const len = binary.length;  
    const buffer = new Uint8Array(len);  
    for (let i = 0; i < len; i++) {  
        buffer[i] = binary.charCodeAt(i);  
    }  
    return new Blob([buffer], { type: 'application/pdf' });  
}

// PDF base64 转地址
export function blobToUrl(blob) {  
    return URL.createObjectURL(blob);  
}

4、插件支持预览CA电子签名及腾讯电子签名,可兼容PC和移动端的PDF预览。 

注意:如果安装完毕并正确引用后无法加载PDF文件,且控制台无报错原因,请降低改插件的版本例:1.2.1