首页 > 解决方案 > 如何使用 PDFJS/pdfjsLib 的 SimpleViewer 加载多个 PDF 文档

问题描述

我正在使用 PDF.js 中的官方SimpleViewer组件示例,它适用于具有多个页面的单个文档,直到我尝试加载多个文档,但它无法按预期工作。

第一个文档正确加载,第二个文档仅显示加载指示器,没有错误。

我已经在课堂上的 JsFiddle 上重新创建了代码,所以希望有人能帮助我理解哪里出了问题。

https://jsfiddle.net/redfox05/xvpzwLc2

原始示例可在此处找到:https ://github.com/mozilla/pdf.js/tree/master/examples/components

问题

将加载单个文档,不会加载多个文档。只显示加载指标。控制台没有错误。

编码:

class MyPDFViewer {
    constructor( options ) {
        this.pdf_count = 0;
        return this.initPDFViewer( options.urls, options.target );
    }

    initPDFViewer( url_array, target ) {

        if( !Array.isArray( url_array )) {
            url_array = [ url_array ];
        }

        var new_url_array = [ url_array[0], url_array[0] ];
        this.loadMultiplePDF( new_url_array, target );
    }

    loadMultiplePDF( url_array, target ) {
        // Load first PDF via initPDFViewer, and loads the rest in callbacks.
        if( Array.isArray( url_array ) && url_array.length > 0 ) {
            var current_url = url_array.pop();

            // Start to cycle through each pdf, loading the first one
            var container = document.createElement( 'div' );
            container.className = 'pdfContainer';
            container.setAttribute('data-document-index', this.pdf_count);
            target.appendChild( container );

            var load_result = this.loadPDF( current_url, container, this.pdf_count );
            load_result.then(() => {
                this.loadMultiplePDF( url_array, target );
            });
            this.pdf_count++;
        }
    }

    loadPDF( pdf_url, container, pdf_id ) {
        var $this = this;

        // Code based on pdfJS examples/components/simpleviewer.js

        // customizable options for PDF loading
        var pdf_link_target = pdfjsLib.LinkTarget.BLANK;
        var search_param = ''; // optional. For highlighting any search params in the pdf.

        // Insert loading text. Must be inserted OUTSIDE of the pdf container to prevent conflict with pdf viewer, as the pdf viewer seems to get loaded into whatever is inside the container.
        $( container ).before( $( '<span type="text" class="pdf-loading t-text" id="pdf-loading-'+ pdf_id +'"></span>' ).text( 'Loading...' ) );

        var pdf_viewer = document.createElement( 'div' );
        pdf_viewer.setAttribute('data-pdf-id', pdf_id );
        // pdf_viewer.setAttribute('id', 'viewer' );
        pdf_viewer.className = 'pdfViewer';
        container.appendChild( pdf_viewer );

        if (!pdfjsLib || !pdfjsLib.getDocument || !pdfjsViewer || !pdfjsViewer.PDFViewer) {
            console.error("pdfjs-dist library is not properly set-up.");
            return false;
        }

        // The workerSrc property shall be specified.
        // pdfjsLib.GlobalWorkerOptions.workerSrc = "dist/pdf.worker.bundle.js";
    pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdn.jsdelivr.net/gh/mozilla/pdfjs-dist/build/pdf.worker.js';
        
    // Some PDFs need external cmaps.
        var CMAP_URL = "framework/pdfjs-cmaps/";
        var CMAP_PACKED = true;

        // var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf";
        var DEFAULT_URL = pdf_url;
        var SEARCH_FOR = search_param; // try 'Mozilla';

        // Can comment this out, as it's already defined above.
        // var container = document.getElementById( pdfCanvasID );

        var eventBus = new pdfjsViewer.EventBus();

        // (Optionally) enable hyperlinks within PDF files.
        var pdfLinkService = new pdfjsViewer.PDFLinkService({
            eventBus: eventBus,
            externalLinkTarget: pdf_link_target
        });

        // (Optionally) enable find controller.
        var pdfFindController = new pdfjsViewer.PDFFindController({
            eventBus: eventBus,
            linkService: pdfLinkService,
        });

        var pdfViewer = new pdfjsViewer.PDFViewer({
            container: container,
            eventBus: eventBus,
            linkService: pdfLinkService,
            findController: pdfFindController,
        });
        pdfLinkService.setViewer(pdfViewer);

        eventBus.on("pagesinit", function () {
            // We can use pdfViewer now, e.g. let's change default scale.
            pdfViewer.currentScaleValue = "page-width";

            // We can try searching for things.
            if (SEARCH_FOR) {
                pdfFindController.executeCommand("find", { query: SEARCH_FOR });
            }
        });

        // Loading document.
        var loadingTask = pdfjsLib.getDocument({
            url: DEFAULT_URL,
            cMapUrl: CMAP_URL,
            cMapPacked: CMAP_PACKED,
        });
        return loadingTask.promise.then(function (pdfDocument) {
            // Document loaded, specifying document for the viewer and
            // the (optional) linkService.
            pdfViewer.setDocument(pdfDocument);

            pdfLinkService.setDocument(pdfDocument, null);

            // Remove loading text
            $( '#pdf-loading-'+ pdf_id ).remove();
        });

    }
}

var urls = ['https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf', 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'];
var pdf_target = document.getElementById('the-container');

var PDFResume = new MyPDFViewer({
                    urls: urls,
                    target: pdf_target
                });
<!-- This is the version based on simpleviewer -->

<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/mozilla/pdfjs-dist/web/pdf_viewer.css" />
<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
  
<script src="//cdn.jsdelivr.net/gh/mozilla/pdfjs-dist/build/pdf.js"></script>
<script src="//cdn.jsdelivr.net/gh/mozilla/pdfjs-dist/web/pdf_viewer.js"></script>

<h1>PDF.js SimpleViewer example</h1>


<div id="the-container"></div>

标签: javascriptpdfpdf-generationpdfjspdfjs-dist

解决方案


推荐阅读