Record uni-app implements online preview PDF functionality in applets and H5
The author wrote this note is to record the convenience of their later memories, after all, can let me remember should be spent a lot of my time to step on the pit, wow cried out!
- Preview in the applet
- In the small program can call API download file, and then open the file, you can achieve
- First call
downloadFile
Obtain the local file path tempFilePath - Call again
openDocument
You can preview the file in a new page. The API also assigns a fileType parameter, such as PDF, to open the PDF file by specifying the type
uni.downloadFile({ url: 'https://example.com/somefile.pdf', success: function (res) { var filePath = res.tempFilePath; Uni. OpenDocument ({filePath: filePath, success: function (res) {console.log(' openDocument successfully '); uni. }}); }});Copy the code
- For a detailed explanation of the API, visit the openDocument documentation on the official website
- Preview in H5
- According to the normal logic, said to the browser preview file, may first think of is embedded in an a link, but this is can be used for apple’s mobile browser, but android click on a link then can download the files directly, but the user must not satisfied, and boy, do you still let me download, tried to use my cell phone memory, Your development is not easy!
- So the helpless and painful development can only think of ways to achieve Apple Android can directly preview PDF online, at this time you can arrange the PDF.js plug-in, you can go to the official website to download the ZIP file, or the Internet Baidu, this has been sorted out by a lot of big guys, here is a link for my final solution to the problem reference
- This little brother wrote quite clear, basically follow can achieve
<template> <view> <web-view :src="pdfUrl"></web-view> </view> </template> <script> export default { data() { return { PdfUrl: ", from: "}}, onLoad() {pdfUrl: ", from: "}}, onLoad() {pdfUrl: ", "} ", onLoad() { Welcome communication) enclosing pdfUrl = '/ hybrid/HTML/web/viewer. The HTML? file='+encodeURIComponent(pdfUrl) }, } </script>Copy the code
Note here is the plug-in volume is quite big, I feel not so applicable to small program this light project, so it is recommended to use conditional compilation to small programs and h5 differentiate the small program or use the API directly, h5 to use plug-ins, like this after packaging, the volume of a plug-in will not be included in the small program, h5, it doesn’t matter ~