用uniapp做了一个预览pdf,兼容h5,微信小程序,希望可以帮到大家
首先我们需要下载一个插件 ext.dcloud.net.cn/plugin?id=2…
下载完成后把 hybrid 解压
然后放到static目录下
一切就准备就绪了,开始写代码
<template>
<view>
<u-button
type="primary"
:loading="loading"
loadingText="预览pdf"
:customStyle="btuStyle"
@click="preview"
>预览pdf
</u-button>
</view>
</template>
<script>
export default {
data() {
return {
fileUrl: "https://cdn.xxxxxx.com/xxxxx.pdf",
viewerUrl: '../../../static/hybrid/html/web/viewer.html',
pdf_url: '',
loading: false,
btuStyle: {
width: "300rpx",
marginBottom: "20rpx",
},
};
},
onLoad() {
this.pdf_url = `${this.viewerUrl}?file=${encodeURIComponent(this.fileUrl)}`;
},
methods: {
preview() {
let that = this;
// #ifdef H5
uni.navigateTo({
url: `/pages/index/componets/web_view?contractUrl=${this.pdf_url}`,
});
// #endif
// #ifdef MP-WEIXIN
this.loading = true;
uni.getSystemInfo({
success: (res) => {
if (res.platform === "android") {
uni.downloadFile({
url: that.fileUrl,
success: function (res) {
const filePath = res.tempFilePath;
uni.openDocument({
filePath: filePath,
showMenu: true,
success: function (res) {
that.loading = false;
console.log("打开文档成功");
},
fail: function (err) {
that.loading = false;
},
});
},
fail: function () {
that.loading = false;
},
});
} else {
that.loading = false;
uni.navigateTo({
url: `/pages/index/componets/web_view?contractUrl=${this.fileUrl}`,
});
}
},
fail: function (err) {
that.loading = false;
},
});
// #endif
},
},
};
</script>
<style lang="scss" scoped>
</style>
pages/index/componets/web_view 下的代码为
<template>
<view id="web-info">
<web-view :src="src"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
src: '',
}
},
onLoad(option) {
this.src = option.contractUrl
}
}
</script>
项目目录结构