Using pdf.js exception occur JavaScriptException: (ReferenceError): PDFJS is not defined

感情迁移 提交于 2019-12-06 08:49:13

You are just blindly copy pasting javascript code into JSNI block.

Example if in your html js block you have

function test() {
  alert('hello');  
}

In your JSNI

private static native int test() /*-{
    var v = $wnd.test();
    return v;
  }-*/;

Do you notice the use of $wnd

1) HTML should have

    <span>Page: <span id="page_num"></span> of <span id="page_count"></span></span>
    <div>
        <canvas id="the-canvas" width="700" style="border: 1px solid black"></canvas>
    </div>

2) Move pdf.js to local folder ( aovid script tag in html file requesting over internet )

3) Instead add <script src="PDF.js" /> in your module.gwt.xml file. Copy https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js into your GWT's public folder.

4) Modify your JSNI code

/*-{
    var url = 'http://cdn.mozilla.net/pdfjs/tracemonkey.pdf';

    $wnd.PDFJS.disableWorker = true;

    var pdfDoc = null,
        pageNum = 1,
        scale = 0.8,
        canvas =  $wnd.document.getElementById('the-canvas'),
        ctx = canvas.getContext('2d');

    function renderPage(num) {
        // Using promise to fetch the page
        pdfDoc.getPage(num).then(function(page) {
            var viewport = page.getViewport(canvas.width / page.getViewport(1.0).width);
            canvas.height = viewport.height;
            // Render PDF page into canvas context
            var renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };
            page.render(renderContext);
        });


       $wnd.document.getElementById('page_num').textContent = pageNum;
       $wnd.document.getElementById('page_count').textContent = pdfDoc.numPages;
    }
    function goPrevious() {
        if (pageNum <= 1) return;
        pageNum--;
        renderPage(pageNum);
    }

    function goNext() {
        if (pageNum >= pdfDoc.numPages) return;
        pageNum++;
        renderPage(pageNum);
    }

    $wnd.PDFJS.getDocument(url).then(function getPdfHelloWorld(_pdfDoc) {
        pdfDoc = _pdfDoc;
        renderPage(pageNum);
    });​
    }-*/;

5) You should be able to solve Next/Prev similarly. Avoid raising one more question to solve that. You should try doing some "HOMEWork"

JSNI 101: you have to use $wnd.PDFJS instead of PDFJS.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!