赞
踩
目录
前言
- 使用vue-pdf组件实现文件预览功能 并在文件上增加操作按钮
- vue3不支持vue-pdf,vue3项目用pdfjs-dist
1、在根目录下输入一下命令
- npm i pdfjs-dist@2.5.207 --save
- npm i vue-pdf@4.2.0 --save
2、修改pacakge.json文件
- "dependencies": {
- "pdfjs-dist": "2.5.207",
- "vue-pdf": "4.2.0",
- },
- import pdf from 'vue-pdf'
-
- export default {
- name: 'App',
- components: {
- pdf
- },
- ···
- }
<pdf :src="file"></pdf>
<pdf v-for="i in pageNum" :key="i" :src="file" :page="i"></pdf>
- export default {
- ···
- data () {
- return {
- file: "/pdf/test.pdf"
- }
- }
- }
- export default {
- ···
- data () {
- return {
- file: "/pdf/test.pdf",
- pageNum: 1
- }
- },
- methods: {
- getPageNum () {
- let loadingTask = pdf.createLoadingTask(this.file)
- loadingTask.promise.then(pdf => {
- this.pageNum = pdf.numPages
- }).catch(err => {
- console.error('pdf加载失败', err);
- })
- }
- },
- mounted () {
- this.getPageNum()
- }
- }
- <template>
- <div class="pdf_wrap">
- <pdf class="pdfView" v-for="item in pageNum" :key="item" :src="pdfUrl" :page="item"></pdf>
- <div class="btnCont">
- <div class="savebtn"
- @click="sign">确认</div>
- </div>
- </div>
- </template>
-
- <script>
- import pdf from 'vue-pdf'
- import { protocolGet } from "../../../api/validation/shareagreement";//调用的接口
- export default {
- components: {
- pdf
- },
- props: {},
- data() {
- return {
- title: this.$route.meta?.title || '',
- pdfUrl:'',
- pageNum: 1
- }
- },
- watch: {},
- computed: {},
- methods: {
- getprotocolGet(){
- protocolGet().then((res)=>{
- if(res.code==200){
- this.pdfUrl= res.data.contractUrl//获取到的协议展示
- this.getPageNum();//pdf分页处理
- }
- })
- },
- getPageNum () {
- let loadingTask = pdf.createLoadingTask(this.pdfUrl,{withCredentials: false})
- loadingTask.promise.then(pdf => {
- this.pageNum = pdf.numPages
- }).catch(err => {
- console.error('pdf加载失败', err);
- })
- },
- sign() {
- this.$router.push({
- path: '/xxx',
- })
- },
- },
- created() {
- this.getprotocolGet()
- },
- mounted() {
-
- },
- }
- </script>
- <style>
- .pdf_wrap{
- height: 100%;
- padding-bottom: 1.4rem;
- background-color: #fff;
- }
- </style>
- <style scoped>
- .pdf_wrap .btnCont {
- position: fixed;
- bottom: 0rem;
- left: 0;
- background-color: #fff;
- padding: 0.1rem 0 .40rem 0;
- width: 100%;
- border: 0;
- text-align: center;
-
- }
- .pdf_wrap .btnCont .savebtn{
- color: #fff;
- display: inline-block;
- height: 0.8rem;
- line-height: 0.8rem;
- border-radius: 0.4rem;
- width: 6.9rem;
- margin: auto;
- font-size: 0.28rem;
- background-color: #ff0b95;
- }
- </style>
1、这种情况就是跨域了找后台解决一下即可
2、 这种情况是pdf还没加载出来就去渲染导致页面pageNum找不到,调用接口加载完成后再去渲染pageNum
3、报这个错误加上 {withCredentials: false} ,报错就没有了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。