在开发中常常会遇到需要在一个应用里打开一份pdf文件并预览,经真机调试时发现在苹果手机上打开pdf文件能正常预览,但在安卓手机打开时却会需要我们下载才能预览,无法直接预览
为了解决这个问题,我们采用安装pdfH5插件的方式,代码如下:
1、安装pdfh5插件
npm i -S pdfh5
2、构建一个pdhH5组件
javascript
<script>
import { computed, onMounted } from "vue";
import { useRoute } from 'vue-router'
import Pdfh5 from "pdfh5";
import "pdfh5/css/pdfh5.css";
export default {
beforeRouteEnter: (to, from, next) => {
if (to.query.name) {
to.name = to.query.name
}
next()
},
setup() {
const route = useRoute()
onMounted(() => {
let pdfurl = decodeURIComponent(route.query.pdfUrl)
let pdfh5 = null
//实例化
pdfh5 = new Pdfh5("#PDF", {
pdfurl: pdfurl,
});
});
},
};
</script>
<template>
<div id="PDF" class="view-pdf"></div>
</template>
<style lang="scss" scoped>
.view-pdf {
width: 100%;
height: 100vh;
}
</style>
3、在路由文件引入pfdH5组件
javascript
{
path: 'pdfView'
name:'pdfView',
component: () => import('../components/pdfH5.vue')
}
4、在业务组件跳转到pdfH5组件
javascript
const handleClickPdf = () => {
router.push({
path:'/xxx/pdfview'
query: {
// pdfUr1是需要跳转的pdf文件的静态资源所在地址
// name是浏览器顶部显示的文件标题
pdfUr1: encodeURIComponent('xxx/xxx'),
name: '条款及细则',
}
})
}