pdfviewer.js 13.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Modified (and JQuerified) from PDF-JS sample code (viewer.js) 
 */
/* globals: PDFJS as defined in pdf.js.  Also assumes that jquery is included. */

//
// Disable workers to avoid yet another cross-origin issue (workers need the URL of
// the script to be loaded, and currently do not allow cross-origin scripts)
//
PDFJS.disableWorker = true;

(function($) {
    $.fn.PDFViewer = function(options) {
        var pdfViewer = this;

        var pdfDocument = null;
30
        var urlToLoad = null;
31
        if (options.url) {
32
            urlToLoad = options.url;
33
        }
34
        var chapterUrls = null;
35
        if (options.chapters) {
36
            chapterUrls = options.chapters;
37
        }
38
        var chapterToLoad = 1;
39 40 41
        if (options.chapterNum) {
            // TODO: this should only be specified if there are 
            // chapters, and it should be in-bounds.
42
            chapterToLoad = options.chapterNum;
43
        }
44
        var pageToLoad = 1;
45
        if (options.pageNum) {
46
            pageToLoad = options.pageNum;
47 48
        }

49 50 51
        var chapterNum = 1;
        var pageNum = 1;

52 53 54 55 56 57 58
        var viewerElement = document.getElementById('viewer');
        var ANNOT_MIN_SIZE = 10;
        var DEFAULT_SCALE_DELTA = 1.1;
        var UNKNOWN_SCALE = 0;
        var MIN_SCALE = 0.25;
        var MAX_SCALE = 4.0;

59 60 61 62
        var currentScale = UNKNOWN_SCALE;
        var currentScaleValue = "0";
        var DEFAULT_SCALE_VALUE = "1";

63
        var setupText = function setupText(textdiv, content, viewport) {
64 65

            function getPageNumberFromDest(dest) {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
                var destPage = 1;
                if (dest instanceof Array) {
                    var destRef = dest[0]; 
                    if (destRef instanceof Object) {
                        // we would need to look this up in the 
                        // list of all pages that have been loaded,
                        // but we're trying to not have to load all the pages
                        // right now.  
                        // destPage = this.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'];
                    } else {
                        destPage = (destRef + 1);
                    }
                }
                return destPage;
            }
81

82
            function bindLink(link, dest) {
83 84
                // get page number from dest:
                destPage = getPageNumberFromDest(dest);
85 86 87 88 89 90
                link.href = '#page=' + destPage;
                link.onclick = function pageViewSetupLinksOnclick() {
                    if (dest && dest instanceof Array )
                        renderPage(destPage);
                    return false;
                };
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
            }

            function createElementWithStyle(tagName, item, rect) {
                if (!rect) {
                    rect = viewport.convertToViewportRectangle(item.rect);
                    rect = PDFJS.Util.normalizeRect(rect);
                }
                var element = document.createElement(tagName);
                element.style.left = Math.floor(rect[0]) + 'px';
                element.style.top = Math.floor(rect[1]) + 'px';
                element.style.width = Math.ceil(rect[2] - rect[0]) + 'px';
                element.style.height = Math.ceil(rect[3] - rect[1]) + 'px';
                // BW: my additions here, but should use css:
                // TODO: move these to css
                element.style.position = 'absolute';
                element.style.cursor = 'auto';

                return element;
            }

            function createTextAnnotation(item) {
                var container = document.createElement('section');
                container.className = 'annotText';
                var rect = viewport.convertToViewportRectangle(item.rect);
                rect = PDFJS.Util.normalizeRect(rect);
                // sanity check because of OOo-generated PDFs
                if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
                    rect[3] = rect[1] + ANNOT_MIN_SIZE;
                }
                if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
                    rect[2] = rect[0] + (rect[3] - rect[1]);
                    // make it square
                }
                var image = createElementWithStyle('img', item, rect);
                var iconName = item.name;
            }


            content.getAnnotations().then(function(items) {
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    switch (item.type) {
                        case 'Link':
                            var link = createElementWithStyle('a', item);
                            link.href = item.url || '';
                            if (!item.url)
                                bindLink(link, ('dest' in item) ? item.dest : null);
                            textdiv.appendChild(link);
                            break;
                        case 'Text':
                            var textAnnotation = createTextAnnotation(item);
                            if (textAnnotation)
                                textdiv.appendChild(textAnnotation);
                            break;
                    }
                }
            });
        }
149

150 151 152 153
        //
        // Get page info from document, resize canvas accordingly, and render page
        //
        renderPage = function(num) {
154 155 156 157
            // don't try to render a page that cannot be rendered
            if (num < 1 || num > pdfDocument.numPages) {
                return;
            }
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
            // Update logging:
            log_event("book", { "type" : "gotopage", "old" : pageNum, "new" : num });

            parentElement = viewerElement;
            while (parentElement.hasChildNodes())
                parentElement.removeChild(parentElement.lastChild);

            // Using promise to fetch the page
            pdfDocument.getPage(num).then(function(page) {
                var viewport = page.getViewport(currentScale);

                var pageDisplayWidth = viewport.width;
                var pageDisplayHeight = viewport.height;

                var pageDivHolder = document.createElement('div');
                pageDivHolder.className = 'pdfpage';
                pageDivHolder.style.width = pageDisplayWidth + 'px';
                pageDivHolder.style.height = pageDisplayHeight + 'px';
                parentElement.appendChild(pageDivHolder);

                // Prepare canvas using PDF page dimensions
                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                canvas.width = pageDisplayWidth;
                canvas.height = pageDisplayHeight;
                pageDivHolder.appendChild(canvas);

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext : context,
                    viewport : viewport
                };
                page.render(renderContext);

                // Prepare and populate text elements layer
                setupText(pageDivHolder, page, viewport);

            });
            pageNum = num;

            // Update page counters
            document.getElementById('numPages').textContent = 'of ' + pdfDocument.numPages;
            $("#pageNumber").max = pdfDocument.numPages;
            $("#pageNumber").val(pageNum);
        }

        // Go to previous page
        prevPage = function prev_page() {
            if (pageNum <= 1)
                return;
            renderPage(pageNum - 1);
            log_event("book", { "type" : "prevpage", "new" : pageNum });
        }

        // Go to next page
        nextPage = function next_page() {
            if (pageNum >= pdfDocument.numPages)
                return;
            renderPage(pageNum + 1);
            log_event("book", { "type" : "nextpage", "new" : pageNum });
        }

        selectScaleOption = function(value) {
222
            var options = $('#scaleSelect options');
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            var predefinedValueFound = false;
            for (var i = 0; i < options.length; i++) {
                var option = options[i];
                if (option.value != value) {
                    option.selected = false;
                    continue;
                }
                option.selected = true;
                predefinedValueFound = true;
            }
            return predefinedValueFound;
        }

        setScale = function pdfViewSetScale(val, resetAutoSettings, noScroll) {
            if (val == currentScale)
                return;
            currentScale = val;
            var customScaleOption = $('#customScaleOption')[0];
            customScaleOption.selected = false
            var predefinedValueFound = selectScaleOption('' + currentScale);
            if (!predefinedValueFound) {
                customScaleOption.textContent = Math.round(currentScale * 10000) / 100 + '%';
                customScaleOption.selected = true;
            }
            $('#zoom_in').disabled = (currentScale === MAX_SCALE);
            $('#zoom_out').disabled = (currentScale === MIN_SCALE);

            // Just call renderPage once the scale
            // has been changed.  If we were saving information about
            // the rendering of other pages, we would need
            // to reset those as well.
            renderPage(pageNum);
        };

        parseScale = function pdfViewParseScale(value, resetAutoSettings, noScroll) {
            // we shouldn't be choosing the 'custom' value -- it's only for display.  
            // Check, just in case.
            if ('custom' == value)
                return;

            var scale = parseFloat(value);
            if (scale) {
                currentScaleValue = value;
                setScale(scale, true, noScroll);
                return;
            }
        };

        zoomIn = function pdfViewZoomIn() {
            var newScale = (currentScale * DEFAULT_SCALE_DELTA).toFixed(2);
            newScale = Math.min(MAX_SCALE, newScale);
            parseScale(newScale, true);
        };

        zoomOut = function pdfViewZoomOut() {
            var newScale = (currentScale / DEFAULT_SCALE_DELTA).toFixed(2);
            newScale = Math.max(MIN_SCALE, newScale);
            parseScale(newScale, true);
        };

        //
        // Asynchronously download PDF as an ArrayBuffer
        //
286 287
        loadUrl = function pdfViewLoadUrl(url, page) {
            PDFJS.getDocument(url).then(
288 289
                function getDocument(_pdfDocument) {
                    pdfDocument = _pdfDocument;
290 291 292 293 294 295 296 297 298 299 300
                    pageNum = page;
                    // if the scale has not been set before, set it now.
                    // Otherwise, don't change the current scale,
                    // but make sure it gets refreshed.
                    if (currentScale == UNKNOWN_SCALE) {
                        parseScale(DEFAULT_SCALE_VALUE);
                    } else {
                        var preservedScale = currentScale;
                        currentScale = UNKNOWN_SCALE;
                        parseScale(preservedScale);
                    }
301 302 303 304 305 306 307 308 309
                }, 
                function getDocumentError(message, exception) {
                    // placeholder: don't expect errors :)
                }, 
                function getDocumentProgress(progressData) {
                    // placeholder: not yet ready to display loading progress
                });
            }; 

310 311 312 313 314 315
        loadChapterUrl = function pdfViewLoadChapterUrl(chapterNum, pageVal) {
            if (chapterNum < 1 || chapterNum > chapterUrls.length) {
                return;
            }
            var chapterUrl = chapterUrls[chapterNum-1];
            loadUrl(chapterUrl, pageVal);
316
        }
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

        $("#previous").click(function(event) {
            prevPage();
        });

        $("#next").click(function(event) {
            nextPage();
        });

        $('#zoom_in').click(function(event) {
            zoomIn();
        });
        $('#zoom_out').click(function(event) {
            zoomOut();
        });

        $('#scaleSelect').change(function(event) {
            parseScale(this.value);
        });
336

337

338
        $('#pageNumber').change(function(event) {
339 340 341 342
            var newPageVal = parseInt(this.value);
            if (newPageVal) {
                renderPage(newPageVal);
            }
343
        });
344 345

        // define navigation links for chapters:  
346
        if (chapterUrls != null) {
347 348
            var loadChapterUrlHelper = function(i) {
                return function(event) {
349 350
                    // when opening a new chapter, always open the first page:
                    loadChapterUrl(i, 1);
351 352
                };
            };
353
            for (var index = 1; index <= chapterUrls.length; index += 1) {
354 355 356 357
                $("#pdfchapter-" + index).click(loadChapterUrlHelper(index));
            }   
        }

358 359 360
        // finally, load the appropriate url/page
        if (urlToLoad != null) {
            loadUrl(urlToLoad, pageToLoad);
361
        } else {
362
            loadChapterUrl(chapterToLoad, pageToLoad);
363 364 365
        }       
            
        return pdfViewer;
366 367
    }
})(jQuery);