1. 程式人生 > 程式設計 >vue使用pdf.js預覽pdf檔案的方法

vue使用pdf.js預覽pdf檔案的方法

我們在頁面進行pdf預覽的時候,由於有些檔案不能夠進行列印和下載,這時候我們使用window自帶的pdf就很難滿足客戶的需求,因此需要另外的辦法來支援我們進行特殊條件的pdf檔案預覽,這裡我採用引入pdf.檔案的形式來達到目的。

第一步:下載pdf.js  

    引入pdf.js檔案

    地址如下:http://mozilla..io/pdf.js/getting_started/

    vue使用pdf.js預覽pdf檔案的方法

第二步,引入

  我這裡是把下http://www.cppcns.com載下來的檔案放在了根目錄的piblic下

vue使用pdf.js預覽pdf檔案的方法

第三步,使用

  主要是地址"/build/generic/web/viewer.html?file="+href,href為請求後端返回的檔案路徑或者後端返回檔案流前段解析後生成的檔案路徑,前面拼接上/build/generic/web/viewer.html?file=,地址為自己引入pdf.js檔案的路徑,也可以直接這樣寫/build/generic/web/viewer.html,他會直接去找。下面我使用的是前段解析檔案流生成地址預覽的。

  預覽方法window.open("/build/generic/web/viewer.html?file="+href);

axios({
                method: 'get',url:url,headers: {
                    "token":auth,},responseType: 'blob',}).then(response => {
                type_ = type_.toLowerCase();
                if (type_ == "docx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                } else if (type_ == "doc") {
                    that._type_ = "application/msword"
                } else if (type_ == "gif") {
                    that._type_ = "image/gif"
                } else if (type_ == "jpeg" || type_ == "jpg") {
                    that._type_ = "image/jpeg"
                } else if (type_ == "png") {
                    that._type_ = "image/png"
                } else if (type_ == "pdf") {
                    that._type_ = "application/pdf"
                } else if (type_ == "txt") {
                    that._type_ = "text/plain;charset=utf-8'"
                } else if (type_ == "xls") {
                    that._type_ = "application/vnd.ms-excel" 
                } else if (type_ == "xlsx") {
                    that._type_ = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                }else if (type_ == "zip") {
                    that._type_ = "application/zip"
                } else if (type_ == "www.cppcns.com
ppt") { that._type_ = "application/vnd.ms-powerpoint" } else if (type_ == "pptx") { that._type_ = "application/vnd.openxmlformats-officedocument.presentationml.presentation" } if(type_ == "pdf"){ var blob = new Blob([response.data],{ type: that._type_ }) LzdVZpPL
var href = window.URL.createObjectURL(blob); //建立下載的連結 window.open("/build/generic/web/viewer.html?file="+href); } })

最後

  如果你想要的禁掉pdf檔案的下載、列印等功能,最簡單的方法是,找的自己匯入檔案裡的viewer.html,路徑為build下的generic資料夾下的web裡的viewer.html,如下:

  vue使用pdf.js預覽pdf檔案的方法

  在這個html裡找到對應下載的dom直接display:none就可以,切記不可以注掉,www.cppcns.com注掉會報錯。如下,紅色框中,一個是下載一個是列印,直接隱藏就可以。

vue使用pdf.js預覽pdf檔案的方法

如果有人問這樣也不安全,那可以和客戶商量不在頁面展示,因為只要頁面可以看到的東西,截圖也可以截下來,註定是不安全的。

到此這篇關於vue使用http://www.cppcns.compdf.js來進行pdf預覽的文章就介紹到這了,更多相關vue使用pdf.js預覽pdf內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!