38
头图

Hello everyone. I was very busy in the first half of the year, and I haven't posted any articles. Someone missed me. In the past two days, I found that someone privately asked me about PDF-related content .

So good, I can feel at ease to catch fish, I am going across an article to introduce how to use PDFJS .

What is PDF.js?

PDF.js is supported by Mozilla. The goal is to create a universal, web standards-based platform for parsing and rendering PDF.

Preview PDF

Use iframe, embed, new window to open

test address , the scheme is relatively simple, belongs to watch the day to eat , all depends on the browser father reward.

How to use

<embed src="https://www.lilnong.top/static/pdf/B-4-RxJS%E5%9C%A8React%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8-%E9%BE%99%E9%80%B8%E6%A5%A0_.pdf">
<iframe src="https://www.lilnong.top/static/pdf/B-4-RxJS%E5%9C%A8React%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8-%E9%BE%99%E9%80%B8%E6%A5%A0_.pdf"></iframe>

Test Results

BrowsercompatibilityWith pictures
Chrome(PC)(Mac)stand byimage.png
safari(PC)(Mac)stand byimage.png
Firefox(PC)(Mac)stand byimage.png
Firefox(PC)(Windows)stand byimage.png
Edge(PC)(Windows)stand byimage.png
IE(PC)(Windows)not supportimage.png
WeChat (Android) (vivo x27)not supportimage.png
Chrome(Android)(vivo x27)not supportimage.png
QQ browser (Android) (vivo x27)not supportimage.png

Advantages: simple, supports most PC browsers (not supported by IE). Cross-domain resources are also available (cors not required)
Disadvantages: Mobile browsers are not supported, and low-version browsers such as IE are not supported. The style cannot be customized.

pdfjs-view

test address , the program compatibility is relatively good, the resources need to be in the same domain or cors cross-domain, and the style can be customized.

How to use

  1. Deploy a pdfjs-view by yourself. (Recommended, more stable)

    1. Download the project, and then the project is divided into two versions /web/viewer-1.html and /legacy/web/viewer.html . Legacy supports lower version browsers and is written in es5. It is reasonable to adopt this solution, and you must also be compatible with all browsers. (If not, just generate a copy of gulp generic-legacy
    2. Then copy the relevant content to your directory and upload it to FTP.
    3. Essentially it is an HTML file, so you can make some modifications to it, such as theme color , hidden download button and so on.
  2. Use CDN or the official pdfjs-view. (Not recommended, unstable, abnormal CORS)

    1. https://mozilla.github.io/pdf.js/legacy/web/viewer.html
    2. https://mozilla.github.io/pdf.js/web/viewer.html
<iframe src="https://www.lilnong.top/static/project?file=https://www.lilnong.top/static/pdf/B-4-RxJS%E5%9C%A8React%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8-%E9%BE%99%E9%80%B8%E6%A5%A0_.pdf"></iframe>
<iframe src="https://www.lilnong.top/static/project/pdfjs-es5-2.5.207/web/viewer-1.html?file=https://www.lilnong.top/static/pdf/B-4-RxJS%E5%9C%A8React%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8-%E9%BE%99%E9%80%B8%E6%A5%A0_.pdf"></iframe>

Test Results

BrowsercompatibilityCompatible ES5 versionWith pictures
Chrome(PC)(Mac)stand bystand byimage.png
safari(PC)(Mac)stand bystand byimage.png
Firefox(PC)(Mac)stand bystand byimage.png
Firefox(PC)(Windows)stand bystand byimage.png
Edge(PC)(Windows)stand bystand byimage.png
IE(PC)(Windows)not supportstand byimage.png
WeChat (Android) (vivo x27)stand bystand byimage.png
Chrome(Android)(vivo x27)stand bystand byimage.png
QQ browser (Android) (vivo x27)stand bystand byimage.png

Same as above, you can see that IE supports it, and the mobile terminal is also OK.

Advantages: support most browsers (PC, M terminal support). Cross-domain resources require cors. The style can be customized.
Disadvantage: Need to deploy a view.

pdfjs-canvas

test address , the solution is more complicated, you need to implement a set of preview matching content (pagination, zoom in and zoom out).

How to use

(function() {
    let el = document.getElementById('canvasWrap');
    if (!el) {
        el = document.createElement('div')
        el.id = 'canvasWrap'
        document.body.appendChild(el)
    }
    el.innerHTML = ''
    let winW = document.documentElement.clientWidth
    // 加载 pdf 资源
    let loadingTask = pdfjsLib.getDocument('https://www.lilnong.top/static/pdf/B-4-RxJS%E5%9C%A8React%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8-%E9%BE%99%E9%80%B8%E6%A5%A0_.pdf')
    // PDF 加载完成的回调。
    loadingTask.promise.then(function(pdf) {
        console.log('pdf', pdf)
        // 可以获取到总页数。
        let pageNum = pdf.numPages
        var _pageNum = 1;
        var renderPageToCanvas = function(pageNum, auto=false) {
            // 获取其中的一个页面
            pdf.getPage(pageNum).then(function(page) {
                // you can now use *page* here
                _pageNum = pageNum
                // 获取原始大小的数据
                var viewport = page.getViewport({
                    scale: 1,
                });
                var scale = (500 / viewport.width).toFixed(2)
                viewport = page.getViewport({
                    scale: scale
                });
                var canvas = document.createElement('canvas');
                el.appendChild(canvas)
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                
                // 创建了一个canvas画板用来存放
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                page.render(renderContext);
                if (auto)
                    renderPageToCanvas(pageNum + 1, auto);
            });
        }
        renderPageToCanvas(_pageNum, true);
        canvasPrev.onclick = function() {
            renderPageToCanvas(Math.max(_pageNum - 1, 1));
        }
        canvasNext.onclick = function() {
            renderPageToCanvas(Math.min(_pageNum + 1, pdf.numPages));
        }
    }, function(reason) {
        console.error(reason)
    })

}
)()

Test Results

BrowsercompatibilityWith pictures
Chrome(PC)(Mac)stand byimage.png
safari(PC)(Mac)stand byimage.png
Firefox(PC)(Mac)stand byimage.png
Firefox(PC)(Windows)stand byimage.png
Edge(PC)(Windows)stand byimage.png
IE(PC)(Windows)not supportimage.png
WeChat (Android) (vivo x27)stand byimage.png
Chrome(Android)(vivo x27)stand byimage.png
QQ browser (Android) (vivo x27)stand byimage.png

Compatibility is also ok, you need to rely on canvas.

Download PDF

  1. Download header
  2. Open directly

    1. If the browser does not support parsing PDF, it can trigger the download.
    2. If the browser supports parsing PDF, it will become a preview.
    1. At this time, we can add download to the a tag to trigger the download. (Need to be in the same domain)

in conclusion

We can through the contents of the above achieve front-end PDF preview function , we summarize the features of each program.

ProgramMobilePC (higher version browser)PC (IE, lower version browser)Cross-domainCopy contentCustom style (pagination, download, etc.)
iframe❌(The platform does not support)❌(The platform does not support)
embed❌(The platform does not support)❌(The platform does not support)✅(CORS)
pdfjs-view❌(ES6 new features)✅(CORS)✅(Modify based on the original foundation)
pdfjs-view-es5✅(CORS)✅(Modify based on the original foundation)
pdfjs-canvas❌(canvas)✅(CORS)❌(canvas)✅(It is completely necessary to implement a complete set of operations by yourself)

Ok, what else is needed, please leave a message. I will update it inside.


linong
29.2k 声望9.5k 粉丝

Read-Search-Ask