Repository: legalthings/angular-pdfjs-viewer Branch: master Commit: 8e6f63ed283e Files: 12 Total size: 45.7 KB Directory structure: gitextract_t6mp9u9b/ ├── .gitignore ├── Gruntfile.js ├── LICENSE ├── README.md ├── demo/ │ ├── app.js │ ├── bower.json │ ├── index.html │ ├── package.json │ └── server.js ├── dist/ │ └── angular-pdfjs-viewer.js ├── package.json └── src/ └── angular-pdfjs-viewer.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ bin/ node_modules/ bower_components/ demo/node_modules/ demo/bower_components/ ================================================ FILE: Gruntfile.js ================================================ module.exports = function (grunt) { 'use strict'; var escapeContent = function(content, quoteChar) { var bsRegexp = new RegExp('\\\\', 'g'); var quoteRegexp = new RegExp('\\' + quoteChar, 'g'); var trimRegexp = new RegExp('\\s*\\+\\s*\\n' + quoteChar + '$'); var nlReplace = '\\n' + quoteChar + ' +\n' + quoteChar; return '\'' + content.replace(bsRegexp, '\\\\').replace(quoteRegexp, '\\' + quoteChar).replace(/\r?\n/g, nlReplace).replace(trimRegexp, '') + '\''; }; // Project configuration. grunt.initConfig({ replace: { dist: { options: { patterns: [ { match: /templateUrl:.*/, replacement: function () { var content = grunt.file.read('vendor/pdf.js-viewer/viewer.html'); return 'template: ' + escapeContent(content, '\'') + ','; } }, { match: /=== get current script file ===[\w\W]+======/, replacement: '' } ] }, files: [ {expand: true, flatten: true, src: ['src/angular-pdfjs-viewer.js'], dest: 'dist/'} ] } } }); /** * Load required Grunt tasks. These are installed based on the versions listed * in `package.json` when you do `npm install` in this directory. */ grunt.loadNpmTasks('grunt-replace'); // Default task(s). grunt.registerTask('default', ['replace']); }; ================================================ FILE: LICENSE ================================================ Copyright (c) LegalThings Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # PDF.js viewer Angular directive Embed Mozilla's [PDF.js](https://mozilla.github.io/pdf.js/) viewer into your angular application, maintaining that look and feel of pdf's we all love. The directive embeds the [full viewer](https://mozilla.github.io/pdf.js/web/viewer.html), which allows you to scroll through the pdf. ## Low maintenance We're no longer using this library ourselves. We'll merge pull requests and create new releases, but not actively solve issues. ![viewer-example](https://cloud.githubusercontent.com/assets/5793511/24605022/6dd5abee-1867-11e7-881a-0d68dc7c77f3.png) ## Installation npm install angular-pdfjs-viewer --save ### Browser supperort Chrome, FireFox, Safari and Egde. ## Usage Below you will find a basic example of how the directive can be used. Note that the order of the scripts matters. Stick to the order of dependencies as shown in the example below. Also note that images, translations and such are being loaded from the `web` folder. ### View ```html Angular PDF.js demo
``` ### Controller ```js angular.module('app', ['pdfjsViewer']); angular.module('app').controller('AppCtrl', function($scope) { $scope.pdf = { src: 'example.pdf', }; }); ``` ## Directive options The `` directive takes the following attributes. #### `src` The source should point to the URL of a publicly available pdf. Note that the `src` must be passed in as an interpolation string. ```html ``` ```javascript $scope.pdf.src = "http://example.com/file.pdf"; ``` --- #### `data` In the case that you cannot simply use the URL of the pdf, you can pass in raw data as a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) object. The `data` attribute takes a scope variable as its argument. ```html ``` ```javascript $scope.data = null; // this is loaded async $http.get("http://example.com/file.pdf", { responseType: 'arraybuffer' }).then(function (response) { $scope.pdf.data = new Uint8Array(response.data); }); ``` --- #### `scale` The `scale` attribute can be used to obtain the current scale (zoom level) of the PDF. The value will be stored in the variable specified. **This is read only**. ```html ``` --- #### `download, print, open` These buttons are by default all visible in the toolbar and can be hidden. ```html ``` --- #### `on-init` The `on-init` function is called when PDF.JS is fully loaded. ```html ``` ```javascript $scope.onInit = function () { // pdf.js is initialized } ``` --- #### `on-page-load` The `on-page-load` function is each time a page is loaded and will pass the page number. When the scale changes all pages are unloaded, so `on-page-load` will be called again for each page. _If `onPageLoad()` returns `false`, the page will not be marked as loaded and `onPageLoad` will be called again for that page on the next (200ms) interval._ ```html ``` ```javascript $scope.onPageLoad = function (page) { // page is loaded }; ``` --- ## Styling The `` directive automatically expands to the height and width of its first immediate parent, in the case of the example `.some-pdf-container`. If no parent container is given the html `body` will be used. Height and width are required to properly display the contents of the pdf. ## Demo You can test out a [demo](https://github.com/legalthings/angular-pdfjs-viewer/tree/master/demo) of this directive. You must run the node server first due to CORS. First make sure the dependencies are installed. cd demo npm install bower install Afterwards run the server like so. node server.js The server will be running on localhost:8080 ## Advanced configuration By default the location of PDF.js assets are automatically determined. However if you place them on alternative locations they may not be found. If so, you can configure these locations. You may disable using the [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). This is useful if you want to add pdf.worker.js to your concatenated JavaScript file. However this will have a negative effect on the runtime performance. As part of your build process you might include all your library scripts within a concatenated Javascript file whilst excluding the pdf.worker.js file. Use setWorkerSrc() to point to the pdf.worker.js script. angular.module('app').config(function(pdfjsViewerConfigProvider) { pdfjsViewerConfigProvider.setWorkerSrc("/assets/pdf.js-viewer/pdf.worker.js"); pdfjsViewerConfigProvider.setCmapDir("/assets/pdf.js-viewer/cmaps"); pdfjsViewerConfigProvider.setImageDir("/assets/pdf.js-viewer/images"); pdfjsViewerConfigProvider.disableWorker(); pdfjsViewerConfigProvider.setVerbosity("infos"); // "errors", "warnings" or "infos" }); Note that a number of images used in the PDF.js viewer are loaded by the `viewer.css`. You can't configure these through JavaScript. Instead you need to compile the `viewer.less` file as lessc --global-var='pdfjsImagePath=/assets/pdf.js-viewer/images' viewer.less viewer.css ================================================ FILE: demo/app.js ================================================ angular.module('app', ['pdfjsViewer']); angular.module('app').controller('AppCtrl', function ($scope, $http, $timeout) { var url = 'example.pdf'; $scope.pdf = { src: url, // get pdf source from a URL that points to a pdf data: null // get pdf source from raw data of a pdf }; getPdfAsArrayBuffer(url).then(function (response) { $scope.pdf.data = new Uint8Array(response.data); }, function (err) { console.log('failed to get pdf as binary:', err); }); function getPdfAsArrayBuffer (url) { return $http.get(url, { responseType: 'arraybuffer', headers: { 'foo': 'bar' } }); } }); ================================================ FILE: demo/bower.json ================================================ { "name": "angular-pdfjs-demo", "description": "Angular PDF.js demo", "license": "MIT", "private": "true", "dependencies": { "angular": "^1.5.8", "pdf.js-viewer": "~1.6.211" } } ================================================ FILE: demo/index.html ================================================ Angular PDF.js demo
================================================ FILE: demo/package.json ================================================ { "name": "angular-pdfjs", "description": "Embed PDF.js into your angular application", "version": "1.0.0", "dependencies": { "bower": "^1.5.2", "cors": "^2.7.1", "express": "^4.13.3" }, "scripts": { "postinstall": "bower install" }, "license": "proprietary" } ================================================ FILE: demo/server.js ================================================ var express = require('express'); var cors = require('cors'); var app = express(); var server = require('http').Server(app); var path = require('path'); app.use(cors()); app.use(express.static(__dirname)); app.get('/angular-pdfjs-viewer.js', function(req, res) { res.sendFile(path.resolve(__dirname + '/../dist/angular-pdfjs-viewer.js')); }); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); server.listen(8080, function () { console.log('Server is listening on localhost:8080'); }); ================================================ FILE: dist/angular-pdfjs-viewer.js ================================================ /** * angular-pdfjs * https://github.com/legalthings/angular-pdfjs * Copyright (c) 2015 ; Licensed MIT */ +function () { 'use strict'; var module = angular.module('pdfjsViewer', []); module.provider('pdfjsViewerConfig', function() { var config = { workerSrc: null, cmapDir: null, imageResourcesPath: null, disableWorker: false, verbosity: null }; this.setWorkerSrc = function(src) { config.workerSrc = src; }; this.setCmapDir = function(dir) { config.cmapDir = dir; }; this.setImageDir = function(dir) { config.imageDir = dir; }; this.disableWorker = function(value) { if (typeof value === 'undefined') value = true; config.disableWorker = value; }; this.setVerbosity = function(level) { config.verbosity = level; }; this.$get = function() { return config; } }); module.run(['pdfjsViewerConfig', function(pdfjsViewerConfig) { if (pdfjsViewerConfig.workerSrc) { PDFJS.workerSrc = pdfjsViewerConfig.workerSrc; } if (pdfjsViewerConfig.cmapDir) { PDFJS.cMapUrl = pdfjsViewerConfig.cmapDir; } if (pdfjsViewerConfig.imageDir) { PDFJS.imageResourcesPath = pdfjsViewerConfig.imageDir; } if (pdfjsViewerConfig.disableWorker) { PDFJS.disableWorker = true; } if (pdfjsViewerConfig.verbosity !== null) { var level = pdfjsViewerConfig.verbosity; if (typeof level === 'string') level = PDFJS.VERBOSITY_LEVELS[level]; PDFJS.verbosity = pdfjsViewerConfig.verbosity; } }]); module.directive('pdfjsViewer', ['$interval', function ($interval) { return { template: '\n' + '
\n' + '\n' + '
\n' + '
\n' + '
\n' + ' \n' + ' \n' + ' \n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + ' \n' + ' \n' + '
\n' + '
\n' + '\n' + '
\n' + ' \n' + '\n' + ' \n' + '\n' + '
\n' + '
\n' + '
\n' + '
\n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + ' \n' + '
\n' + '
\n' + ' \n' + '\n' + ' \n' + '\n' + ' \n' + '\n' + ' \n' + ' \n' + ' Current View\n' + ' \n' + '\n' + '
\n' + '\n' + ' \n' + '
\n' + '
\n' + '
\n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + ' \n' + ' \n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + '
\n' + '\n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + '\n' + '
\n' + '
\n' + '
\n' + '\n' + ' \n' + '
\n' + '\n' + ' \n' + '\n' + '
\n' + '
\n' + '
', restrict: 'E', scope: { onInit: '&', onPageLoad: '&', scale: '=?', src: '@?', data: '=?' }, link: function ($scope, $element, $attrs) { $element.children().wrap('
'); var initialised = false; var loaded = {}; var numLoaded = 0; if (!window.PDFJS) { return console.warn("PDFJS is not set! Make sure that pdf.js is loaded before angular-pdfjs-viewer.js is loaded."); } // initialize the pdf viewer with (with empty source) window.PDFJS.webViewerLoad(""); function onPdfInit() { initialised = true; if ($attrs.removeMouseListeners === "true") { window.removeEventListener('DOMMouseScroll', handleMouseWheel); window.removeEventListener('mousewheel', handleMouseWheel); var pages = document.querySelectorAll('.page'); angular.forEach(pages, function (page) { angular.element(page).children().css('pointer-events', 'none'); }); } if ($scope.onInit) $scope.onInit(); } var poller = $interval(function () { if (!window.PDFViewerApplication) { return; } var pdfViewer = window.PDFViewerApplication.pdfViewer; if (pdfViewer) { if ($scope.scale !== pdfViewer.currentScale) { loaded = {}; numLoaded = 0; $scope.scale = pdfViewer.currentScale; } } else { console.warn("PDFViewerApplication.pdfViewer is not set"); } var pages = document.querySelectorAll('.page'); angular.forEach(pages, function (page) { var element = angular.element(page); var pageNum = element.attr('data-page-number'); if (!element.attr('data-loaded')) { delete loaded[pageNum]; return; } if (pageNum in loaded) return; if (!initialised) onPdfInit(); if ($scope.onPageLoad) { if ($scope.onPageLoad({page: pageNum}) === false) return; } loaded[pageNum] = true; numLoaded++; }); }, 200); $element.on('$destroy', function() { $interval.cancel(poller); }); // watch pdf source $scope.$watchGroup([ function () { return $scope.src; }, function () { return $scope.data; } ], function (values) { var src = values[0]; var data = values[1]; if (!src && !data) { return; } window.PDFViewerApplication.open(src || data); }); // watch other attributes $scope.$watch(function () { return $attrs; }, function () { if ($attrs.open === 'false') { document.getElementById('openFile').setAttribute('hidden', 'true'); document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true'); } if ($attrs.download === 'false') { document.getElementById('download').setAttribute('hidden', 'true'); document.getElementById('secondaryDownload').setAttribute('hidden', 'true'); } if ($attrs.print === 'false') { document.getElementById('print').setAttribute('hidden', 'true'); document.getElementById('secondaryPrint').setAttribute('hidden', 'true'); } if ($attrs.width) { document.getElementById('outerContainer').style.width = $attrs.width; } if ($attrs.height) { document.getElementById('outerContainer').style.height = $attrs.height; } }); } }; }]); }(); ================================================ FILE: package.json ================================================ { "name": "angular-pdfjs-viewer", "description": "Embed PDF.js viewer into your angular application", "homepage": "http://github.com/legalthings/angular-pdfjs-viewer", "license": "MIT", "version": "1.0.0", "contributors": [ "LegalThings ", "Moesjarraf ", "Arnold Daniels " ], "dependencies": { "angular": "^1.5.8", "pdf.js-viewer": "~1.6.211" }, "license": "MIT", "main": "dist/angular-pdfjs-viewer.js", "devDependencies": { "grunt": "^0.4.5", "grunt-replace": "^0.10.2" } } ================================================ FILE: src/angular-pdfjs-viewer.js ================================================ /** * angular-pdfjs * https://github.com/legalthings/angular-pdfjs * Copyright (c) 2015 ; Licensed MIT */ +function () { 'use strict'; var module = angular.module('pdfjsViewer', []); module.provider('pdfjsViewerConfig', function() { var config = { workerSrc: null, cmapDir: null, imageResourcesPath: null, disableWorker: false, verbosity: null }; this.setWorkerSrc = function(src) { config.workerSrc = src; }; this.setCmapDir = function(dir) { config.cmapDir = dir; }; this.setImageDir = function(dir) { config.imageDir = dir; }; this.disableWorker = function(value) { if (typeof value === 'undefined') value = true; config.disableWorker = value; }; this.setVerbosity = function(level) { config.verbosity = level; }; this.$get = function() { return config; } }); module.run(['pdfjsViewerConfig', function(pdfjsViewerConfig) { if (pdfjsViewerConfig.workerSrc) { PDFJS.workerSrc = pdfjsViewerConfig.workerSrc; } if (pdfjsViewerConfig.cmapDir) { PDFJS.cMapUrl = pdfjsViewerConfig.cmapDir; } if (pdfjsViewerConfig.imageDir) { PDFJS.imageResourcesPath = pdfjsViewerConfig.imageDir; } if (pdfjsViewerConfig.disableWorker) { PDFJS.disableWorker = true; } if (pdfjsViewerConfig.verbosity !== null) { var level = pdfjsViewerConfig.verbosity; if (typeof level === 'string') level = PDFJS.VERBOSITY_LEVELS[level]; PDFJS.verbosity = pdfjsViewerConfig.verbosity; } }]); module.directive('pdfjsViewer', ['$interval', function ($interval) { return { templateUrl: file.folder + '../../pdf.js-viewer/viewer.html', restrict: 'E', scope: { onInit: '&', onPageLoad: '&', scale: '=?', src: '@?', data: '=?' }, link: function ($scope, $element, $attrs) { $element.children().wrap('
'); var initialised = false; var loaded = {}; var numLoaded = 0; if (!window.PDFJS) { return console.warn("PDFJS is not set! Make sure that pdf.js is loaded before angular-pdfjs-viewer.js is loaded."); } // initialize the pdf viewer with (with empty source) window.PDFJS.webViewerLoad(""); function onPdfInit() { initialised = true; if ($attrs.removeMouseListeners === "true") { window.removeEventListener('DOMMouseScroll', handleMouseWheel); window.removeEventListener('mousewheel', handleMouseWheel); var pages = document.querySelectorAll('.page'); angular.forEach(pages, function (page) { angular.element(page).children().css('pointer-events', 'none'); }); } if ($scope.onInit) $scope.onInit(); } var poller = $interval(function () { if (!window.PDFViewerApplication) { return; } var pdfViewer = window.PDFViewerApplication.pdfViewer; if (pdfViewer) { if ($scope.scale !== pdfViewer.currentScale) { loaded = {}; numLoaded = 0; $scope.scale = pdfViewer.currentScale; } } else { console.warn("PDFViewerApplication.pdfViewer is not set"); } var pages = document.querySelectorAll('.page'); angular.forEach(pages, function (page) { var element = angular.element(page); var pageNum = element.attr('data-page-number'); if (!element.attr('data-loaded')) { delete loaded[pageNum]; return; } if (pageNum in loaded) return; if (!initialised) onPdfInit(); if ($scope.onPageLoad) { if ($scope.onPageLoad({page: pageNum}) === false) return; } loaded[pageNum] = true; numLoaded++; }); }, 200); $element.on('$destroy', function() { $interval.cancel(poller); }); // watch pdf source $scope.$watchGroup([ function () { return $scope.src; }, function () { return $scope.data; } ], function (values) { var src = values[0]; var data = values[1]; if (!src && !data) { return; } window.PDFViewerApplication.open(src || data); }); // watch other attributes $scope.$watch(function () { return $attrs; }, function () { if ($attrs.open === 'false') { document.getElementById('openFile').setAttribute('hidden', 'true'); document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true'); } if ($attrs.download === 'false') { document.getElementById('download').setAttribute('hidden', 'true'); document.getElementById('secondaryDownload').setAttribute('hidden', 'true'); } if ($attrs.print === 'false') { document.getElementById('print').setAttribute('hidden', 'true'); document.getElementById('secondaryPrint').setAttribute('hidden', 'true'); } if ($attrs.width) { document.getElementById('outerContainer').style.width = $attrs.width; } if ($attrs.height) { document.getElementById('outerContainer').style.height = $attrs.height; } }); } }; }]); // === get current script file === var file = {}; file.scripts = document.querySelectorAll('script[src]'); file.path = file.scripts[file.scripts.length - 1].src; file.filename = getFileName(file.path); file.folder = getLocation(file.path).pathname.replace(file.filename, ''); function getFileName(url) { var anchor = url.indexOf('#'); var query = url.indexOf('?'); var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length); return url.substring(url.lastIndexOf('/', end) + 1, end); } function getLocation(href) { var location = document.createElement("a"); location.href = href; if (!location.host) location.href = location.href; // Weird assigment return location; } // ====== }();