This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge
preface
In the process of writing a project, there will be occasional use of PDF files. When we want to see a PDF file, do you want to download the PDF file first and view the PDF file through the dedicated software installed on the computer to open THE PDF file? What if there’s a requirement to not let users install the software? After all, many users don’t know how to install the software or what it needs to open. Ok, there is such a need that we also have to achieve it, after all, this reason we can not refute ah.
thinking
Now that it’s out there, let’s figure out how to use it. I’m going to use PDF. I wonder if there is any library file that can be operated by JS to help me? Decisive baidu, we today’s protagonist will come: PDFJS.
Library directory parsing and downloading
Now that you have a plan, it is time to study it. First of all, you need to download the file of this library.Let me download. This page will have two, one is compatible with the old version, you can download according to their own actual situation ah.The downloaded code structure is as follows:There are two folders:
- Build here is the core PDF file
- Examples of web
Method of use
There are two ways to use it. One is to preview the PDF file by using the core library file, and the other is to preview the PDF file by using the examples given. Here is to preview the PDF file with the example given, if you are interested in studying how to use the core file to achieve it.
File location
First, we need to put the downloaded file into the static directory of the vue project, as shown in the figure below:
The actual call
Where needed, use the following method:
var url = encodeURIComponent(window.location.origin+'/other/202101/dc88623a-74c4-49c4-bc95-7e34d9cf6163.pdf') window.open(window.location.origin + window.location.pathname+'static/pdfjs/web/viewer.html? file='+url)Copy the code
The above PDF address is your local path, where the path can be relative and absolute path, the above is the absolute path
You should see the following effect:
The problem
If the PDF file address and the current download library file address in the same domain, should not be too big a problem, if different domains need to solve cross-domain issues. One area that needs to be addressed is the library file that we downloaded. Find the following comment in the viewer. Js file:Comment on the contents in the red box above. If the server is given the download address, you can use iframe nesting to solve this problem.
conclusion
In fact, you can see that cross-domain knowledge is sometimes very useful, the above is used, I just started to get how can not come out, later found that cross-domain download can not come down. There are more current usage and questions, welcome to ask.