As a junior front-end engineer, I encountered a thorny problem, which is to display the pdf file on the mobile terminal. Of course, the first thing I did not encounter was Baidu. There is pdf.js on the Internet, but there is a direct lazy one in vue The components of npm, because I am a government project, the project code cannot be used, I use my own code offline to demonstrate.
The first step is npm install --save vue-pdf
<template>
<div>
<div>pdf预览</div>
<pdf
:src="pdfUrl"// src需要展示的PDF地址
v-for="i in numPages" :key="i" :page="i"> // 多页显示></pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: {
pdf
},
data(){
return{
pdfUrl: '',
numPages:1, // pdf 文件总页数。
}
},
mounted: function() {
this.getNumPages("http://www.gov.cn/zhengce/pdfFile/2020_PDF.pdf")
},
methods: {
getNumPages(url) {
let loadingTask = pdf.createLoadingTask(url)
//这个方法创建一个当前pdf的加载任务,可以作为:src使用或者公开的获取当前pdf的页面总数;
loadingTask.then(pdf => {
this.url = loadingTask
this.numPages = pdf.numPages
}).catch((err) => {
console.error('pdf加载失败')
})
},
}
}
</script>
API Props attributes :srcString/Object The pdf link can be a relative, absolute address or a pdf loading task; :pageNumber-default:1 Need to display the first few pages of the pdf; :rotateNumber-default:0 The rotation angle of pdf, the multiple of '90' is valid; Events callback @password(updatePassword,reason) updatePassword: The function prompts the password that needs to be entered; reason:提示('NEED_PASSWORD' or 'INCORRECT_PASSWORD'); @progressNumber Loading progress of the pdf page, Rang[0,1]; @page-loadedNumber Callback when a pdf page is loaded successfully, number is the index value of the page; @ num-pagesNumber Monitor the pdf loading and get the number of pages of the pdf; @errorObject pdf loading failure callback; @link-clickedNumber Triggered when the stand-alone internal link; Public methods print(dpi,pageList) Call the browser print function; dpi printing resolution (100) pageList array of pages to be printed Public static methods createLoadingTask(src) This method creates a loading task of the current pdf, which can be used as: src or publicly obtain the total number of pages of the current pdf; Detailed explanation: https://www.cnblogs.com/lodadssd/p/10297989.html