描述
因爲項目是使用wepy框架開發的,所以語法上面如果大家是使用其它的方案要注意下,其實思路和核心代碼大體上相同。、
思路
首先,做這個功能得知道,ios使用web-view標籤是直接可以瀏覽pdf的,但是安卓系統的手機是不可以的,這個時候我們一般採用先下載,然後再打開的方式瀏覽。只要是藉助小程序的wx.downloadFile
、wx.openDocument
事件實現這個功能。然後再區分ios和安卓使用不同的方法。
上代碼
頁面部分
<web-view wx:if="{{iosTrue}}" src="{{src}}"></web-view>
js邏輯
data = {
src: "",
iosTrue: false,
system: "",
};
onLoad(option) {
//因爲可能路徑帶參數,小程序跳轉時會省略,所以我在這裏做了轉碼
this.src = decodeURIComponent(option.pdfId);
this.$apply();
this.getPhoneModel();
}
//判斷手機系統,執行不同的方案
getPhoneModel() {
var that = this;
wx.getSystemInfo({
success: function(res) {
console.log(res.system);
that.system = res.system;
var str = "iOS";
if (that.system.indexOf(str) != -1) {
//IOS環境
that.iosTrue = true;
console.log("IOS環境");
that.$apply();
} else {
this.androidPdf()
console.log("安卓環境");
}
that.$apply();
}
});
}
androidPdf() {
wx.downloadFile({
url: this.src,
// filePath: `${wx.env.USER_DATA_PATH}/` +'xxx.pdf', // 如果你發現你下載的pdf文件後綴爲unknown,導致不可預料,你可以自己定義文件名字
success: function(res) {
console.log(res);
// var Path = res.filePath //自己定義的文件名,返回的時候就不是tempFilePath字段了,注意下。
var Path = res.tempFilePath; //返回的文件臨時地址,用於後面打開本地預覽所用
// that.webview=Path
console.log(Path);
wx.openDocument({
// filePath: `${wx.env.USER_DATA_PATH}/` +'xxx.pdf', //當然也可以不用上面的路徑,直接打開你自己定義的文件名字,但是這個前提是你前面使用的是自定義的文件名
filePath: Path,
fileType: "pdf", //後綴爲unknown的話,可以直接以pdf的格式打開,也可以。我就是用這種,都行,反正開心就好。
success: function(res) {
console.log("打開文檔成功");
}
});
},
fail: function(res) {
console.log(res);
}
});
}
到這裏就結束了,很簡單的實現。
個人水平有限,有問題歡迎大家留言指導,僅供學習和參考。
學海無涯!努力二字,共勉!