vue uses pdf.js to browse pdf and hide downloading and printing

1. Download pdf.js

https://mozilla.github.io/pdf.js/
Insert image description here

2.Create a folder

Create a pdfjs folder in public. After decompressing the downloaded package, pull build and web into the pdfjs folder.

3. Provide the url of the pdf

① If the backend returns a url, perform the following operations. However, errors may be reported due to cross-domain.

Mosaic on this page

//encodeURIComponent可以避免pdfjs识别错file=xxx?id=xx类型地址的file参数,但可以自动解码,不需要自己解码
<iframe 
:src="`/pdfjs/web/viewer.html?file=${encodeURIComponent(this.pdfUrl)}`" 
frameborder="0" 
class="pdf-window">
></iframe>

New page opens

function(){
    
    
	window.open(`/pdfjs/web/viewer.html?file=${
      
      encodeURIComponent(this.pdfUrl)}`)
}

② If it is a file stream, convert it into a url. You can refer to the previous article.

https://blog.csdn.net/q249859693/article/details/131457499?spm=1001.2014.3001.5502

4. Hide downloading and printing

In the pdfjs folder you created in the web

①Viewer.html file search id="download"

Add style="display:none" download (download) print (print) in the position below


Insert image description here

②Viewer.js file search eventBus._on(“download”, webViewerDownload);

In the picture below, comment these two lines of code
Insert image description here

5. Report an error

①Cross-domain

Insert image description here

Many people say to comment the following code in viewer.js, but it didn’t work when I tried.

 if (fileOrigin !== viewerOrigin) {
    
    
    throw new Error("file origin does not match viewer's");
 }
You can add an agent

The pdf address is http://xxx/…
vue.config, in js

 proxy: {
    
    
    '/pdf': {
    
    
        target: 'https://xxx',
        pathRewrite: {
    
     '^/pdf': '' },
        ws: false,
        changeOrigin: true
      }
}

Modify url

const url = pdfurl.replace('http://xxx/', location.origin + '/pdf/')
window.open(`/pdfjs/web/viewer.html?file=${
      
      encodeURIComponent(url)}`)

② The file is damaged or encrypted

Insert image description here

③403

It may be due to the token or other reasons, so you must not be able to view the pdfUrl even if you open it in the browser. If you can open it after downloading, you can use the URL returned by the download interface or the returned stream to convert it into a URL. This is the problem I have. That way there’s no need to cross domains.
Insert image description here

おすすめ

転載: blog.csdn.net/q249859693/article/details/131458696