Front-end implementation of pdf preview in vue (including usage of vue-pdf plugin)

 

Scenario: The front end needs to realize the preview function of pdf according to the online pdf address returned by the back end.

Situation 1: The pdf address returned by the backend can be directly previewed in the browser by pasting it into the url box of the browser.

Method (1) You can directly use window.open('acquired pdf address') to re-open a browser tab, and directly realize the preview function through the browser tab (the style of the preview page will be slightly different depending on the browser) Differences)

eg: Effect in Google-Chrome browser

242dae8571454c7eaaef6b403a08ee74.png

 

Method (2) If you do not want to reopen the browser tab, you can add an iframe tag to the current page to preview the pdf to be previewed. The preview interface style displayed in the iframe tag is the same as the method (1) above, and it follows the browser.

<iframe
    :src="获取到的pdf预览地址"
>
</iframe>

 

Case 2: The pdf address returned by the backend is pasted into the url box of the browser, and cannot be previewed directly in the browser. (The situation I encountered before was that after the url was entered in the browser, the browser did not display the page and started the download directly)

Note: In this case, the above two methods cannot be previewed. The handsome men and beauties at the front end must confirm the status of the returned url in advance!

Method (3) Use the plugin vue-pdf to preview

step

1. Install dependencies

npm install --save vue-pdf

2. On the required page, introduce the plug-in

import pdf from 'vue-pdf'

 3. use

3.1 Single-page pdf can be used directly

<pdf>
    :src="获取到的pdf地址"
</pdf>

3.2 Multi-page pdf is realized by loop 

html tag part

​
<pdf
    v-for="item in pageTotal"
    :src="pdfUrl"
    :key="item"
    :page="item"
>
</pdf>

In the mounted function, the following method needs to be called to obtain the total number of pages of the pdf

// 获取pdf总页数
getTotal() {
    // 多页pdf的src中不能直接使用后端获取的pdf地址 否则会按页数请求多次数据
    // 需要使用下述方法的返回值作为url
    this.pdfUrl = pdf.createLoadingTask('获取到的pdf地址')
    // 获取页码
    this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {})
}

At this point, the page can normally realize the pdf preview

 

Guess you like

Origin blog.csdn.net/m0_71537867/article/details/129918181