diff --git a/.eslintrc b/.eslintrc index 2bbb0d3ce..1e1aff530 100644 --- a/.eslintrc +++ b/.eslintrc @@ -11,6 +11,10 @@ "unicorn", ], + "extends": [ + "plugin:prettier/recommended" + ], + "env": { "browser": true, "es6": true, @@ -47,7 +51,6 @@ "no-empty": ["error", { "allowEmptyCatch": true, }], "no-ex-assign": "error", "no-extra-boolean-cast": "error", - "no-extra-semi": "error", "no-func-assign": "error", "no-inner-declarations": ["error", "functions"], "no-invalid-regexp": "error", @@ -84,9 +87,6 @@ "no-implied-eval": "error", "no-iterator": "error", "no-lone-blocks": "error", - "no-multi-spaces": ["error", { - "ignoreEOLComments": true, - }], "no-multi-str": "error", "no-new-func": "error", "no-new-wrappers": "error", @@ -127,48 +127,16 @@ }], // Stylistic Issues - "array-bracket-spacing": ["error", "never"], - "block-spacing": ["error", "always"], - "brace-style": ["error", "1tbs", { - "allowSingleLine": false, - }], - "comma-dangle": ["error", { - "arrays": "ignore", - "objects": "always", - "imports": "never", - "exports": "always", - "functions": "never", - }], - "comma-spacing": ["error", { "before": false, "after": true, }], - "comma-style": ["error", "last"], - "eol-last": "error", - "func-call-spacing": ["error", "never"], - "key-spacing": ["error", { "beforeColon": false, "afterColon": true, "mode": "strict", }], - "keyword-spacing": ["error", { "before": true, "after": true, }], - "linebreak-style": ["error", "unix"], "lines-between-class-members": ["error", "always"], "max-len": ["error", { - "code": 80, + "code": 1000, + "comments": 80, "ignoreUrls": true }], "new-cap": ["error", { "newIsCap": true, "capIsNew": false, }], - "new-parens": "error", "no-array-constructor": "error", "no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 0, "maxBOF": 1, }], "no-new-object": "error", - "no-tabs": "error", - "no-trailing-spaces": ["error", { "skipBlankLines": false, }], - "no-whitespace-before-property": "error", - "object-curly-spacing": ["error", "always"], - "operator-linebreak": ["error", "after", { "overrides": { ":": "ignore", } }], - "quotes": ["error", "single"], - "semi-spacing": ["error", { "before": false, "after": true, }], - "semi": ["error", "always"], - "space-before-blocks": ["error", "always"], - "space-before-function-paren": ["error", { "anonymous": "ignore", "named": "never", }], - "space-in-parens": ["error", "never"], - "space-infix-ops": ["error", { "int32Hint": false }], - "space-unary-ops": ["error", { "words": true, "nonwords": false, }], "spaced-comment": ["error", "always", { "block": { "balanced": true, @@ -176,12 +144,6 @@ }], // ECMAScript 6 - "arrow-body-style": ["error", "always"], - "arrow-parens": ["error", "always"], - "arrow-spacing": ["error", { - "before": true, - "after": true, - }], "constructor-super": "error", "no-class-assign": "error", "no-confusing-arrow": "error", @@ -197,7 +159,6 @@ "avoidQuotes": true, }], "prefer-const": "off", - "rest-spread-spacing": ["error", "never"], "sort-imports": ["error", { "ignoreCase": true, }], diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..f5289b11c --- /dev/null +++ b/.prettierrc @@ -0,0 +1,8 @@ +{ + "endOfLine": "lf", + "printWidth": 80, + "semi": true, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false +} diff --git a/examples/acroforms/acroforms.js b/examples/acroforms/acroforms.js index 125c3aa83..75a0c8650 100644 --- a/examples/acroforms/acroforms.js +++ b/examples/acroforms/acroforms.js @@ -13,15 +13,15 @@ * limitations under the License. */ -'use strict'; +"use strict"; pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; -var DEFAULT_URL = '../../test/pdfs/f1040.pdf'; +var DEFAULT_URL = "../../test/pdfs/f1040.pdf"; var DEFAULT_SCALE = 1.0; -var container = document.getElementById('pageContainer'); +var container = document.getElementById("pageContainer"); // Fetch the PDF document from the URL using promises. var loadingTask = pdfjsLib.getDocument(DEFAULT_URL); @@ -30,23 +30,24 @@ loadingTask.promise.then(function(doc) { var promise = Promise.resolve(); for (var i = 1; i <= doc.numPages; i++) { - promise = promise.then(function (pageNum) { - return doc.getPage(pageNum).then(function (pdfPage) { - // Create the page view. - var pdfPageView = new pdfjsViewer.PDFPageView({ - container: container, - id: pageNum, - scale: DEFAULT_SCALE, - defaultViewport: pdfPage.getViewport({ scale: DEFAULT_SCALE, }), - annotationLayerFactory: - new pdfjsViewer.DefaultAnnotationLayerFactory(), - renderInteractiveForms: true, - }); + promise = promise.then( + function(pageNum) { + return doc.getPage(pageNum).then(function(pdfPage) { + // Create the page view. + var pdfPageView = new pdfjsViewer.PDFPageView({ + container: container, + id: pageNum, + scale: DEFAULT_SCALE, + defaultViewport: pdfPage.getViewport({ scale: DEFAULT_SCALE }), + annotationLayerFactory: new pdfjsViewer.DefaultAnnotationLayerFactory(), + renderInteractiveForms: true, + }); - // Associate the actual page with the view and draw it. - pdfPageView.setPdfPage(pdfPage); - return pdfPageView.draw(); - }); - }.bind(null, i)); + // Associate the actual page with the view and draw it. + pdfPageView.setPdfPage(pdfPage); + return pdfPageView.draw(); + }); + }.bind(null, i) + ); } }); diff --git a/examples/browserify/gulpfile.js b/examples/browserify/gulpfile.js index 0d382c532..241f97f43 100644 --- a/examples/browserify/gulpfile.js +++ b/examples/browserify/gulpfile.js @@ -1,36 +1,40 @@ -var gulp = require('gulp'); -var browserify = require('browserify'); -var streamify = require('gulp-streamify'); -var rename = require('gulp-rename'); -var uglify = require('gulp-uglify'); -var source = require('vinyl-source-stream'); +var gulp = require("gulp"); +var browserify = require("browserify"); +var streamify = require("gulp-streamify"); +var rename = require("gulp-rename"); +var uglify = require("gulp-uglify"); +var source = require("vinyl-source-stream"); -var OUTPUT_PATH = '../../build/browserify'; -var TMP_FILE_PREFIX = '../../build/browserify_'; +var OUTPUT_PATH = "../../build/browserify"; +var TMP_FILE_PREFIX = "../../build/browserify_"; -gulp.task('build-bundle', function() { - return browserify('main.js', { output: TMP_FILE_PREFIX + 'main.tmp', }) - .ignore(require.resolve('pdfjs-dist/build/pdf.worker')) // Reducing size +gulp.task("build-bundle", function() { + return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" }) + .ignore(require.resolve("pdfjs-dist/build/pdf.worker")) // Reducing size .bundle() - .pipe(source(TMP_FILE_PREFIX + 'main.tmp')) + .pipe(source(TMP_FILE_PREFIX + "main.tmp")) .pipe(streamify(uglify())) - .pipe(rename('main.bundle.js')) + .pipe(rename("main.bundle.js")) .pipe(gulp.dest(OUTPUT_PATH)); }); -gulp.task('build-worker', function() { +gulp.task("build-worker", function() { // We can create our own viewer (see worker.js) or use already defined one. - var workerSrc = require.resolve('pdfjs-dist/build/pdf.worker.entry'); - return browserify(workerSrc, { output: TMP_FILE_PREFIX + 'worker.tmp', }) + var workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry"); + return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" }) .bundle() - .pipe(source(TMP_FILE_PREFIX + 'worker.tmp')) - .pipe(streamify(uglify({ - compress: { - sequences: false, // Chrome has issue with the generated code if true - }, - }))) - .pipe(rename('pdf.worker.bundle.js')) + .pipe(source(TMP_FILE_PREFIX + "worker.tmp")) + .pipe( + streamify( + uglify({ + compress: { + sequences: false, // Chrome has issue with the generated code if true + }, + }) + ) + ) + .pipe(rename("pdf.worker.bundle.js")) .pipe(gulp.dest(OUTPUT_PATH)); }); -gulp.task('build', gulp.series('build-bundle', 'build-worker')); +gulp.task("build", gulp.series("build-bundle", "build-worker")); diff --git a/examples/browserify/main.js b/examples/browserify/main.js index 8554ffc9b..644a10140 100644 --- a/examples/browserify/main.js +++ b/examples/browserify/main.js @@ -3,31 +3,33 @@ // Hello world example for browserify. -var pdfjsLib = require('pdfjs-dist'); +var pdfjsLib = require("pdfjs-dist"); -var pdfPath = '../learning/helloworld.pdf'; +var pdfPath = "../learning/helloworld.pdf"; // Setting worker path to worker bundle. pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../build/browserify/pdf.worker.bundle.js'; + "../../build/browserify/pdf.worker.bundle.js"; // Loading a document. var loadingTask = pdfjsLib.getDocument(pdfPath); -loadingTask.promise.then(function (pdfDocument) { - // Request a first page - return pdfDocument.getPage(1).then(function (pdfPage) { - // Display page on the existing canvas with 100% scale. - var viewport = pdfPage.getViewport({ scale: 1.0, }); - var canvas = document.getElementById('theCanvas'); - canvas.width = viewport.width; - canvas.height = viewport.height; - var ctx = canvas.getContext('2d'); - var renderTask = pdfPage.render({ - canvasContext: ctx, - viewport: viewport, +loadingTask.promise + .then(function(pdfDocument) { + // Request a first page + return pdfDocument.getPage(1).then(function(pdfPage) { + // Display page on the existing canvas with 100% scale. + var viewport = pdfPage.getViewport({ scale: 1.0 }); + var canvas = document.getElementById("theCanvas"); + canvas.width = viewport.width; + canvas.height = viewport.height; + var ctx = canvas.getContext("2d"); + var renderTask = pdfPage.render({ + canvasContext: ctx, + viewport: viewport, + }); + return renderTask.promise; }); - return renderTask.promise; + }) + .catch(function(reason) { + console.error("Error: " + reason); }); -}).catch(function (reason) { - console.error('Error: ' + reason); -}); diff --git a/examples/browserify/worker.js b/examples/browserify/worker.js index edad61c61..3ae28b39f 100644 --- a/examples/browserify/worker.js +++ b/examples/browserify/worker.js @@ -3,5 +3,7 @@ // Hello world example for browserify: worker bundle. -(typeof window !== 'undefined' ? window : {}).pdfjsWorker = - require('pdfjs-dist/build/pdf.worker'); +(typeof window !== "undefined" + ? window + : {} +).pdfjsWorker = require("pdfjs-dist/build/pdf.worker"); diff --git a/examples/components/pageviewer.js b/examples/components/pageviewer.js index d58f4ccb4..626561c5a 100644 --- a/examples/components/pageviewer.js +++ b/examples/components/pageviewer.js @@ -13,28 +13,29 @@ * limitations under the License. */ -'use strict'; +"use strict"; if (!pdfjsLib.getDocument || !pdfjsViewer.PDFPageView) { - alert('Please build the pdfjs-dist library using\n' + - ' `gulp dist-install`'); + alert( + "Please build the pdfjs-dist library using\n" + " `gulp dist-install`" + ); } // The workerSrc property shall be specified. // pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; // Some PDFs need external cmaps. // -var CMAP_URL = '../../node_modules/pdfjs-dist/cmaps/'; +var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; var CMAP_PACKED = true; -var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf'; +var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; var PAGE_TO_VIEW = 1; var SCALE = 1.0; -var container = document.getElementById('pageContainer'); +var container = document.getElementById("pageContainer"); // Loading document. var loadingTask = pdfjsLib.getDocument({ @@ -44,13 +45,13 @@ var loadingTask = pdfjsLib.getDocument({ }); loadingTask.promise.then(function(pdfDocument) { // Document loaded, retrieving the page. - return pdfDocument.getPage(PAGE_TO_VIEW).then(function (pdfPage) { + return pdfDocument.getPage(PAGE_TO_VIEW).then(function(pdfPage) { // Creating the page view with default parameters. var pdfPageView = new pdfjsViewer.PDFPageView({ container: container, id: PAGE_TO_VIEW, scale: SCALE, - defaultViewport: pdfPage.getViewport({ scale: SCALE, }), + defaultViewport: pdfPage.getViewport({ scale: SCALE }), // We can enable text/annotations layers, if needed textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory(), annotationLayerFactory: new pdfjsViewer.DefaultAnnotationLayerFactory(), diff --git a/examples/components/simpleviewer.js b/examples/components/simpleviewer.js index 5a87a4028..3bc1f6a94 100644 --- a/examples/components/simpleviewer.js +++ b/examples/components/simpleviewer.js @@ -13,27 +13,28 @@ * limitations under the License. */ -'use strict'; +"use strict"; if (!pdfjsLib.getDocument || !pdfjsViewer.PDFViewer) { - alert('Please build the pdfjs-dist library using\n' + - ' `gulp dist-install`'); + alert( + "Please build the pdfjs-dist library using\n" + " `gulp dist-install`" + ); } // The workerSrc property shall be specified. // pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; // Some PDFs need external cmaps. // -var CMAP_URL = '../../node_modules/pdfjs-dist/cmaps/'; +var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; var CMAP_PACKED = true; -var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf'; -var SEARCH_FOR = ''; // try 'Mozilla'; +var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; +var SEARCH_FOR = ""; // try 'Mozilla'; -var container = document.getElementById('viewerContainer'); +var container = document.getElementById("viewerContainer"); // (Optionally) enable hyperlinks within PDF files. var pdfLinkService = new pdfjsViewer.PDFLinkService(); @@ -50,12 +51,13 @@ var pdfViewer = new pdfjsViewer.PDFViewer({ }); pdfLinkService.setViewer(pdfViewer); -document.addEventListener('pagesinit', function () { +document.addEventListener("pagesinit", function() { // We can use pdfViewer now, e.g. let's change default scale. - pdfViewer.currentScaleValue = 'page-width'; + pdfViewer.currentScaleValue = "page-width"; - if (SEARCH_FOR) { // We can try search for things - pdfFindController.executeCommand('find', { query: SEARCH_FOR, }); + if (SEARCH_FOR) { + // We can try search for things + pdfFindController.executeCommand("find", { query: SEARCH_FOR }); } }); diff --git a/examples/components/singlepageviewer.js b/examples/components/singlepageviewer.js index d6157f4b1..6ab8cc9e2 100644 --- a/examples/components/singlepageviewer.js +++ b/examples/components/singlepageviewer.js @@ -13,27 +13,28 @@ * limitations under the License. */ -'use strict'; +"use strict"; if (!pdfjsLib.getDocument || !pdfjsViewer.PDFSinglePageViewer) { - alert('Please build the pdfjs-dist library using\n' + - ' `gulp dist-install`'); + alert( + "Please build the pdfjs-dist library using\n" + " `gulp dist-install`" + ); } // The workerSrc property shall be specified. // pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; // Some PDFs need external cmaps. // -var CMAP_URL = '../../node_modules/pdfjs-dist/cmaps/'; +var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; var CMAP_PACKED = true; -var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf'; -var SEARCH_FOR = ''; // try 'Mozilla'; +var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; +var SEARCH_FOR = ""; // try 'Mozilla'; -var container = document.getElementById('viewerContainer'); +var container = document.getElementById("viewerContainer"); // (Optionally) enable hyperlinks within PDF files. var pdfLinkService = new pdfjsViewer.PDFLinkService(); @@ -50,12 +51,13 @@ var pdfSinglePageViewer = new pdfjsViewer.PDFSinglePageViewer({ }); pdfLinkService.setViewer(pdfSinglePageViewer); -document.addEventListener('pagesinit', function () { +document.addEventListener("pagesinit", function() { // We can use pdfSinglePageViewer now, e.g. let's change default scale. - pdfSinglePageViewer.currentScaleValue = 'page-width'; + pdfSinglePageViewer.currentScaleValue = "page-width"; - if (SEARCH_FOR) { // We can try search for things - pdfFindController.executeCommand('find', { query: SEARCH_FOR, }); + if (SEARCH_FOR) { + // We can try search for things + pdfFindController.executeCommand("find", { query: SEARCH_FOR }); } }); diff --git a/examples/image_decoders/jpeg_viewer.js b/examples/image_decoders/jpeg_viewer.js index 5e2eae152..e84307cf9 100644 --- a/examples/image_decoders/jpeg_viewer.js +++ b/examples/image_decoders/jpeg_viewer.js @@ -13,39 +13,40 @@ * limitations under the License. */ -'use strict'; +"use strict"; if (!pdfjsImageDecoders.JpegImage) { - alert('Please build the pdfjs-dist library using `gulp dist-install`'); + alert("Please build the pdfjs-dist library using `gulp dist-install`"); } -var JPEG_IMAGE = 'fish.jpg'; +var JPEG_IMAGE = "fish.jpg"; -var jpegCanvas = document.getElementById('jpegCanvas'); -var jpegCtx = jpegCanvas.getContext('2d'); +var jpegCanvas = document.getElementById("jpegCanvas"); +var jpegCtx = jpegCanvas.getContext("2d"); // Load the image data, and convert it to a Uint8Array. // var nonBinaryRequest = false; var request = new XMLHttpRequest(); -request.open('GET', JPEG_IMAGE, false); +request.open("GET", JPEG_IMAGE, false); try { - request.responseType = 'arraybuffer'; - nonBinaryRequest = request.responseType !== 'arraybuffer'; + request.responseType = "arraybuffer"; + nonBinaryRequest = request.responseType !== "arraybuffer"; } catch (e) { nonBinaryRequest = true; } if (nonBinaryRequest && request.overrideMimeType) { - request.overrideMimeType('text/plain; charset=x-user-defined'); + request.overrideMimeType("text/plain; charset=x-user-defined"); } request.send(null); var typedArrayImage; if (nonBinaryRequest) { - var str = request.responseText, length = str.length; + var str = request.responseText, + length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { - bytes[i] = str.charCodeAt(i) & 0xFF; + bytes[i] = str.charCodeAt(i) & 0xff; } typedArrayImage = bytes; } else { @@ -57,7 +58,8 @@ if (nonBinaryRequest) { var jpegImage = new pdfjsImageDecoders.JpegImage(); jpegImage.parse(typedArrayImage); -var width = jpegImage.width, height = jpegImage.height; +var width = jpegImage.width, + height = jpegImage.height; var jpegData = jpegImage.getData({ width: width, height: height, @@ -68,7 +70,7 @@ var jpegData = jpegImage.getData({ // var imageData = jpegCtx.createImageData(width, height); var imageBytes = imageData.data; -for (var j = 0, k = 0, jj = width * height * 4; j < jj;) { +for (var j = 0, k = 0, jj = width * height * 4; j < jj; ) { imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++]; diff --git a/examples/mobile-viewer/viewer.js b/examples/mobile-viewer/viewer.js index 099c5b285..e875f72b8 100644 --- a/examples/mobile-viewer/viewer.js +++ b/examples/mobile-viewer/viewer.js @@ -13,26 +13,26 @@ * limitations under the License. */ -'use strict'; +"use strict"; if (!pdfjsLib.getDocument || !pdfjsViewer.PDFViewer) { - alert('Please build the pdfjs-dist library using\n `gulp dist-install`'); + alert("Please build the pdfjs-dist library using\n `gulp dist-install`"); } var USE_ONLY_CSS_ZOOM = true; var TEXT_LAYER_MODE = 0; // DISABLE var MAX_IMAGE_SIZE = 1024 * 1024; -var CMAP_URL = '../../node_modules/pdfjs-dist/cmaps/'; +var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; var CMAP_PACKED = true; pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; -var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf'; +var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; var DEFAULT_SCALE_DELTA = 1.1; var MIN_SCALE = 0.25; var MAX_SCALE = 10.0; -var DEFAULT_SCALE_VALUE = 'auto'; +var DEFAULT_SCALE_VALUE = "auto"; var PDFViewerApplication = { pdfLoadingTask: null, @@ -49,10 +49,12 @@ var PDFViewerApplication = { open: function(params) { if (this.pdfLoadingTask) { // We need to destroy already opened document - return this.close().then(function () { - // ... and repeat the open() call. - return this.open(params); - }.bind(this)); + return this.close().then( + function() { + // ... and repeat the open() call. + return this.open(params); + }.bind(this) + ); } var url = params.url; @@ -68,45 +70,60 @@ var PDFViewerApplication = { }); this.pdfLoadingTask = loadingTask; - loadingTask.onProgress = function (progressData) { + loadingTask.onProgress = function(progressData) { self.progress(progressData.loaded / progressData.total); }; - return loadingTask.promise.then(function (pdfDocument) { - // Document loaded, specifying document for the viewer. - self.pdfDocument = pdfDocument; - self.pdfViewer.setDocument(pdfDocument); - self.pdfLinkService.setDocument(pdfDocument); - self.pdfHistory.initialize({ fingerprint: pdfDocument.fingerprint, }); + return loadingTask.promise.then( + function(pdfDocument) { + // Document loaded, specifying document for the viewer. + self.pdfDocument = pdfDocument; + self.pdfViewer.setDocument(pdfDocument); + self.pdfLinkService.setDocument(pdfDocument); + self.pdfHistory.initialize({ fingerprint: pdfDocument.fingerprint }); - self.loadingBar.hide(); - self.setTitleUsingMetadata(pdfDocument); - }, function (exception) { - var message = exception && exception.message; - var l10n = self.l10n; - var loadingErrorMessage; + self.loadingBar.hide(); + self.setTitleUsingMetadata(pdfDocument); + }, + function(exception) { + var message = exception && exception.message; + var l10n = self.l10n; + var loadingErrorMessage; - if (exception instanceof pdfjsLib.InvalidPDFException) { - // change error message also for other builds - loadingErrorMessage = l10n.get('invalid_file_error', null, - 'Invalid or corrupted PDF file.'); - } else if (exception instanceof pdfjsLib.MissingPDFException) { - // special message for missing PDFs - loadingErrorMessage = l10n.get('missing_file_error', null, - 'Missing PDF file.'); - } else if (exception instanceof pdfjsLib.UnexpectedResponseException) { - loadingErrorMessage = l10n.get('unexpected_response_error', null, - 'Unexpected server response.'); - } else { - loadingErrorMessage = l10n.get('loading_error', null, - 'An error occurred while loading the PDF.'); + if (exception instanceof pdfjsLib.InvalidPDFException) { + // change error message also for other builds + loadingErrorMessage = l10n.get( + "invalid_file_error", + null, + "Invalid or corrupted PDF file." + ); + } else if (exception instanceof pdfjsLib.MissingPDFException) { + // special message for missing PDFs + loadingErrorMessage = l10n.get( + "missing_file_error", + null, + "Missing PDF file." + ); + } else if (exception instanceof pdfjsLib.UnexpectedResponseException) { + loadingErrorMessage = l10n.get( + "unexpected_response_error", + null, + "Unexpected server response." + ); + } else { + loadingErrorMessage = l10n.get( + "loading_error", + null, + "An error occurred while loading the PDF." + ); + } + + loadingErrorMessage.then(function(msg) { + self.error(msg, { message: message }); + }); + self.loadingBar.hide(); } - - loadingErrorMessage.then(function (msg) { - self.error(msg, { message: message, }); - }); - self.loadingBar.hide(); - }); + ); }, /** @@ -115,8 +132,8 @@ var PDFViewerApplication = { * destruction is completed. */ close: function() { - var errorWrapper = document.getElementById('errorWrapper'); - errorWrapper.setAttribute('hidden', 'true'); + var errorWrapper = document.getElementById("errorWrapper"); + errorWrapper.setAttribute("hidden", "true"); if (!this.pdfLoadingTask) { return Promise.resolve(); @@ -140,9 +157,9 @@ var PDFViewerApplication = { }, get loadingBar() { - var bar = new pdfjsViewer.ProgressBar('#loadingBar', {}); + var bar = new pdfjsViewer.ProgressBar("#loadingBar", {}); - return pdfjsLib.shadow(this, 'loadingBar', bar); + return pdfjsLib.shadow(this, "loadingBar", bar); }, setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) { @@ -160,99 +177,125 @@ var PDFViewerApplication = { setTitleUsingMetadata: function(pdfDocument) { var self = this; pdfDocument.getMetadata().then(function(data) { - var info = data.info, metadata = data.metadata; + var info = data.info, + metadata = data.metadata; self.documentInfo = info; self.metadata = metadata; // Provides some basic debug information - console.log('PDF ' + pdfDocument.fingerprint + ' [' + - info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() + - ' / ' + (info.Creator || '-').trim() + ']' + - ' (PDF.js: ' + (pdfjsLib.version || '-') + ')'); + console.log( + "PDF " + + pdfDocument.fingerprint + + " [" + + info.PDFFormatVersion + + " " + + (info.Producer || "-").trim() + + " / " + + (info.Creator || "-").trim() + + "]" + + " (PDF.js: " + + (pdfjsLib.version || "-") + + ")" + ); var pdfTitle; - if (metadata && metadata.has('dc:title')) { - var title = metadata.get('dc:title'); + if (metadata && metadata.has("dc:title")) { + var title = metadata.get("dc:title"); // Ghostscript sometimes returns 'Untitled', so prevent setting the // title to 'Untitled. - if (title !== 'Untitled') { + if (title !== "Untitled") { pdfTitle = title; } } - if (!pdfTitle && info && info['Title']) { - pdfTitle = info['Title']; + if (!pdfTitle && info && info["Title"]) { + pdfTitle = info["Title"]; } if (pdfTitle) { - self.setTitle(pdfTitle + ' - ' + document.title); + self.setTitle(pdfTitle + " - " + document.title); } }); }, setTitle: function pdfViewSetTitle(title) { document.title = title; - document.getElementById('title').textContent = title; + document.getElementById("title").textContent = title; }, error: function pdfViewError(message, moreInfo) { var l10n = this.l10n; - var moreInfoText = [l10n.get('error_version_info', - { version: pdfjsLib.version || '?', - build: pdfjsLib.build || '?', }, - 'PDF.js v{{version}} (build: {{build}})')]; + var moreInfoText = [ + l10n.get( + "error_version_info", + { version: pdfjsLib.version || "?", build: pdfjsLib.build || "?" }, + "PDF.js v{{version}} (build: {{build}})" + ), + ]; if (moreInfo) { moreInfoText.push( - l10n.get('error_message', { message: moreInfo.message, }, - 'Message: {{message}}')); + l10n.get( + "error_message", + { message: moreInfo.message }, + "Message: {{message}}" + ) + ); if (moreInfo.stack) { moreInfoText.push( - l10n.get('error_stack', { stack: moreInfo.stack, }, - 'Stack: {{stack}}')); + l10n.get("error_stack", { stack: moreInfo.stack }, "Stack: {{stack}}") + ); } else { if (moreInfo.filename) { moreInfoText.push( - l10n.get('error_file', { file: moreInfo.filename, }, - 'File: {{file}}')); + l10n.get( + "error_file", + { file: moreInfo.filename }, + "File: {{file}}" + ) + ); } if (moreInfo.lineNumber) { moreInfoText.push( - l10n.get('error_line', { line: moreInfo.lineNumber, }, - 'Line: {{line}}')); + l10n.get( + "error_line", + { line: moreInfo.lineNumber }, + "Line: {{line}}" + ) + ); } } } - var errorWrapper = document.getElementById('errorWrapper'); - errorWrapper.removeAttribute('hidden'); + var errorWrapper = document.getElementById("errorWrapper"); + errorWrapper.removeAttribute("hidden"); - var errorMessage = document.getElementById('errorMessage'); + var errorMessage = document.getElementById("errorMessage"); errorMessage.textContent = message; - var closeButton = document.getElementById('errorClose'); + var closeButton = document.getElementById("errorClose"); closeButton.onclick = function() { - errorWrapper.setAttribute('hidden', 'true'); + errorWrapper.setAttribute("hidden", "true"); }; - var errorMoreInfo = document.getElementById('errorMoreInfo'); - var moreInfoButton = document.getElementById('errorShowMore'); - var lessInfoButton = document.getElementById('errorShowLess'); + var errorMoreInfo = document.getElementById("errorMoreInfo"); + var moreInfoButton = document.getElementById("errorShowMore"); + var lessInfoButton = document.getElementById("errorShowLess"); moreInfoButton.onclick = function() { - errorMoreInfo.removeAttribute('hidden'); - moreInfoButton.setAttribute('hidden', 'true'); - lessInfoButton.removeAttribute('hidden'); - errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px'; + errorMoreInfo.removeAttribute("hidden"); + moreInfoButton.setAttribute("hidden", "true"); + lessInfoButton.removeAttribute("hidden"); + errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px"; }; lessInfoButton.onclick = function() { - errorMoreInfo.setAttribute('hidden', 'true'); - moreInfoButton.removeAttribute('hidden'); - lessInfoButton.setAttribute('hidden', 'true'); + errorMoreInfo.setAttribute("hidden", "true"); + moreInfoButton.removeAttribute("hidden"); + lessInfoButton.setAttribute("hidden", "true"); }; - moreInfoButton.removeAttribute('hidden'); - lessInfoButton.setAttribute('hidden', 'true'); - Promise.all(moreInfoText).then(function (parts) { - errorMoreInfo.value = parts.join('\n'); + moreInfoButton.removeAttribute("hidden"); + lessInfoButton.setAttribute("hidden", "true"); + Promise.all(moreInfoText).then(function(parts) { + errorMoreInfo.value = parts.join("\n"); }); }, @@ -302,7 +345,7 @@ var PDFViewerApplication = { this.l10n = pdfjsViewer.NullL10n; - var container = document.getElementById('viewerContainer'); + var container = document.getElementById("viewerContainer"); var pdfViewer = new pdfjsViewer.PDFViewer({ container: container, linkService: linkService, @@ -318,69 +361,77 @@ var PDFViewerApplication = { }); linkService.setHistory(this.pdfHistory); - document.getElementById('previous').addEventListener('click', function() { + document.getElementById("previous").addEventListener("click", function() { PDFViewerApplication.page--; }); - document.getElementById('next').addEventListener('click', function() { + document.getElementById("next").addEventListener("click", function() { PDFViewerApplication.page++; }); - document.getElementById('zoomIn').addEventListener('click', function() { + document.getElementById("zoomIn").addEventListener("click", function() { PDFViewerApplication.zoomIn(); }); - document.getElementById('zoomOut').addEventListener('click', function() { + document.getElementById("zoomOut").addEventListener("click", function() { PDFViewerApplication.zoomOut(); }); - document.getElementById('pageNumber').addEventListener('click', function() { + document.getElementById("pageNumber").addEventListener("click", function() { this.select(); }); - document.getElementById('pageNumber').addEventListener('change', - function() { - PDFViewerApplication.page = (this.value | 0); + document + .getElementById("pageNumber") + .addEventListener("change", function() { + PDFViewerApplication.page = this.value | 0; - // Ensure that the page number input displays the correct value, - // even if the value entered by the user was invalid - // (e.g. a floating point number). - if (this.value !== PDFViewerApplication.page.toString()) { - this.value = PDFViewerApplication.page; - } - }); + // Ensure that the page number input displays the correct value, + // even if the value entered by the user was invalid + // (e.g. a floating point number). + if (this.value !== PDFViewerApplication.page.toString()) { + this.value = PDFViewerApplication.page; + } + }); - document.addEventListener('pagesinit', function () { + document.addEventListener("pagesinit", function() { // We can use pdfViewer now, e.g. let's change default scale. pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; }); - document.addEventListener('pagechanging', function (evt) { - var page = evt.detail.pageNumber; - var numPages = PDFViewerApplication.pagesCount; + document.addEventListener( + "pagechanging", + function(evt) { + var page = evt.detail.pageNumber; + var numPages = PDFViewerApplication.pagesCount; - document.getElementById('pageNumber').value = page; - document.getElementById('previous').disabled = (page <= 1); - document.getElementById('next').disabled = (page >= numPages); - }, true); + document.getElementById("pageNumber").value = page; + document.getElementById("previous").disabled = page <= 1; + document.getElementById("next").disabled = page >= numPages; + }, + true + ); }, }; -document.addEventListener('DOMContentLoaded', function () { - PDFViewerApplication.initUI(); -}, true); +document.addEventListener( + "DOMContentLoaded", + function() { + PDFViewerApplication.initUI(); + }, + true +); (function animationStartedClosure() { // The offsetParent is not set until the PDF.js iframe or object is visible. // Waiting for first animation. - PDFViewerApplication.animationStartedPromise = new Promise( - function (resolve) { - window.requestAnimationFrame(resolve); - }); + PDFViewerApplication.animationStartedPromise = new Promise(function(resolve) { + window.requestAnimationFrame(resolve); + }); })(); // We need to delay opening until all HTML is loaded. -PDFViewerApplication.animationStartedPromise.then(function () { +PDFViewerApplication.animationStartedPromise.then(function() { PDFViewerApplication.open({ url: DEFAULT_URL, }); diff --git a/examples/node/domstubs.js b/examples/node/domstubs.js index 9c671aae4..dcf1720fc 100644 --- a/examples/node/domstubs.js +++ b/examples/node/domstubs.js @@ -2,10 +2,18 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ function xmlEncode(s) { - var i = 0, ch; + var i = 0, + ch; s = String(s); - while (i < s.length && (ch = s[i]) !== '&' && ch !== '<' && - ch !== '\"' && ch !== '\n' && ch !== '\r' && ch !== '\t') { + while ( + i < s.length && + (ch = s[i]) !== "&" && + ch !== "<" && + ch !== '"' && + ch !== "\n" && + ch !== "\r" && + ch !== "\t" + ) { i++; } if (i >= s.length) { @@ -15,23 +23,23 @@ function xmlEncode(s) { while (i < s.length) { ch = s[i++]; switch (ch) { - case '&': - buf += '&'; + case "&": + buf += "&"; break; - case '<': - buf += '<'; + case "<": + buf += "<"; break; - case '\"': - buf += '"'; + case '"': + buf += """; break; - case '\n': - buf += ' '; + case "\n": + buf += " "; break; - case '\r': - buf += ' '; + case "\r": + buf += " "; break; - case '\t': - buf += ' '; + case "\t": + buf += " "; break; default: buf += ch; @@ -45,9 +53,9 @@ function DOMElement(name) { this.nodeName = name; this.childNodes = []; this.attributes = {}; - this.textContent = ''; + this.textContent = ""; - if (name === 'style') { + if (name === "style") { this.sheet = { cssRules: [], insertRule: function(rule) { @@ -74,7 +82,7 @@ DOMElement.prototype = { // Assuming that there is only one matching attribute for a given name, // across all namespaces. if (NS) { - var suffix = ':' + name; + var suffix = ":" + name; for (var fullName in this.attributes) { if (fullName.slice(-suffix.length) === suffix) { return this.attributes[fullName]; @@ -85,7 +93,7 @@ DOMElement.prototype = { }, setAttribute: function DOMElement_setAttribute(name, value) { - value = value || ''; + value = value || ""; value = xmlEncode(value); this.attributes[name] = value; }, @@ -123,7 +131,7 @@ DOMElement.prototype = { while ((chunk = serializer.getNext()) !== null) { buf.push(chunk); } - return buf.join(''); + return buf.join(""); }, getSerializer: function DOMElement_getSerializer() { @@ -147,37 +155,39 @@ DOMElementSerializer.prototype = { getNext: function DOMElementSerializer_getNext() { var node = this._node; switch (this._state) { - case 0: // Start opening tag. + case 0: // Start opening tag. ++this._state; - return '<' + node.nodeName; - case 1: // Add SVG namespace if this is the root element. + return "<" + node.nodeName; + case 1: // Add SVG namespace if this is the root element. ++this._state; - if (node.nodeName === 'svg:svg') { - return ' xmlns:xlink="http://www.w3.org/1999/xlink"' + - ' xmlns:svg="http://www.w3.org/2000/svg"'; + if (node.nodeName === "svg:svg") { + return ( + ' xmlns:xlink="http://www.w3.org/1999/xlink"' + + ' xmlns:svg="http://www.w3.org/2000/svg"' + ); } - /* falls through */ - case 2: // Initialize variables for looping over attributes. + /* falls through */ + case 2: // Initialize variables for looping over attributes. ++this._state; this._loopIndex = 0; this._attributeKeys = Object.keys(node.attributes); - /* falls through */ - case 3: // Serialize any attributes and end opening tag. + /* falls through */ + case 3: // Serialize any attributes and end opening tag. if (this._loopIndex < this._attributeKeys.length) { var name = this._attributeKeys[this._loopIndex++]; - return ' ' + name + '="' + xmlEncode(node.attributes[name]) + '"'; + return " " + name + '="' + xmlEncode(node.attributes[name]) + '"'; } ++this._state; - return '>'; - case 4: // Serialize textContent for tspan/style elements. - if (node.nodeName === 'svg:tspan' || node.nodeName === 'svg:style') { + return ">"; + case 4: // Serialize textContent for tspan/style elements. + if (node.nodeName === "svg:tspan" || node.nodeName === "svg:style") { this._state = 6; return xmlEncode(node.textContent); } ++this._state; this._loopIndex = 0; - /* falls through */ - case 5: // Serialize child nodes (only for non-tspan/style elements). + /* falls through */ + case 5: // Serialize child nodes (only for non-tspan/style elements). var value; while (true) { value = this._childSerializer && this._childSerializer.getNext(); @@ -193,14 +203,14 @@ DOMElementSerializer.prototype = { break; } } - /* falls through */ - case 6: // Ending tag. + /* falls through */ + case 6: // Ending tag. ++this._state; - return ''; - case 7: // Done. + return ""; + case 7: // Done. return null; default: - throw new Error('Unexpected serialization state: ' + this._state); + throw new Error("Unexpected serialization state: " + this._state); } }, }; @@ -209,7 +219,7 @@ const document = { childNodes: [], get currentScript() { - return { src: '', }; + return { src: "" }; }, get documentElement() { @@ -222,12 +232,12 @@ const document = { }, createElement: function(element) { - return this.createElementNS('', element); + return this.createElementNS("", element); }, getElementsByTagName: function(element) { - if (element === 'head') { - return [this.head || (this.head = new DOMElement('head'))]; + if (element === "head") { + return [this.head || (this.head = new DOMElement("head"))]; } return []; }, @@ -256,13 +266,13 @@ var exported_symbols = Object.keys(exports); exports.setStubs = function(namespace) { exported_symbols.forEach(function(key) { - console.assert(!(key in namespace), 'property should not be set: ' + key); + console.assert(!(key in namespace), "property should not be set: " + key); namespace[key] = exports[key]; }); }; exports.unsetStubs = function(namespace) { exported_symbols.forEach(function(key) { - console.assert(key in namespace, 'property should be set: ' + key); + console.assert(key in namespace, "property should be set: " + key); delete namespace[key]; }); }; diff --git a/examples/node/getinfo.js b/examples/node/getinfo.js index 3df0b2bac..1dade92d5 100644 --- a/examples/node/getinfo.js +++ b/examples/node/getinfo.js @@ -8,60 +8,68 @@ // // Run `gulp dist-install` to generate 'pdfjs-dist' npm package files. -var pdfjsLib = require('pdfjs-dist'); +var pdfjsLib = require("pdfjs-dist"); // Loading file from file system into typed array -var pdfPath = process.argv[2] || '../../web/compressed.tracemonkey-pldi-09.pdf'; +var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf"; // Will be using promises to load document, pages and misc data instead of // callback. var loadingTask = pdfjsLib.getDocument(pdfPath); -loadingTask.promise.then(function(doc) { - var numPages = doc.numPages; - console.log('# Document Loaded'); - console.log('Number of Pages: ' + numPages); - console.log(); - - var lastPromise; // will be used to chain promises - lastPromise = doc.getMetadata().then(function (data) { - console.log('# Metadata Is Loaded'); - console.log('## Info'); - console.log(JSON.stringify(data.info, null, 2)); +loadingTask.promise + .then(function(doc) { + var numPages = doc.numPages; + console.log("# Document Loaded"); + console.log("Number of Pages: " + numPages); console.log(); - if (data.metadata) { - console.log('## Metadata'); - console.log(JSON.stringify(data.metadata.getAll(), null, 2)); - console.log(); - } - }); - var loadPage = function (pageNum) { - return doc.getPage(pageNum).then(function (page) { - console.log('# Page ' + pageNum); - var viewport = page.getViewport({ scale: 1.0, }); - console.log('Size: ' + viewport.width + 'x' + viewport.height); + var lastPromise; // will be used to chain promises + lastPromise = doc.getMetadata().then(function(data) { + console.log("# Metadata Is Loaded"); + console.log("## Info"); + console.log(JSON.stringify(data.info, null, 2)); console.log(); - return page.getTextContent().then(function (content) { - // Content contains lots of information about the text layout and - // styles, but we need only strings at the moment - var strings = content.items.map(function (item) { - return item.str; - }); - console.log('## Text Content'); - console.log(strings.join(' ')); - }).then(function () { + if (data.metadata) { + console.log("## Metadata"); + console.log(JSON.stringify(data.metadata.getAll(), null, 2)); console.log(); - }); + } }); - }; - // Loading of the first page will wait on metadata and subsequent loadings - // will wait on the previous pages. - for (var i = 1; i <= numPages; i++) { - lastPromise = lastPromise.then(loadPage.bind(null, i)); - } - return lastPromise; -}).then(function () { - console.log('# End of Document'); -}, function (err) { - console.error('Error: ' + err); -}); + + var loadPage = function(pageNum) { + return doc.getPage(pageNum).then(function(page) { + console.log("# Page " + pageNum); + var viewport = page.getViewport({ scale: 1.0 }); + console.log("Size: " + viewport.width + "x" + viewport.height); + console.log(); + return page + .getTextContent() + .then(function(content) { + // Content contains lots of information about the text layout and + // styles, but we need only strings at the moment + var strings = content.items.map(function(item) { + return item.str; + }); + console.log("## Text Content"); + console.log(strings.join(" ")); + }) + .then(function() { + console.log(); + }); + }); + }; + // Loading of the first page will wait on metadata and subsequent loadings + // will wait on the previous pages. + for (var i = 1; i <= numPages; i++) { + lastPromise = lastPromise.then(loadPage.bind(null, i)); + } + return lastPromise; + }) + .then( + function() { + console.log("# End of Document"); + }, + function(err) { + console.error("Error: " + err); + } + ); diff --git a/examples/node/pdf2png/pdf2png.js b/examples/node/pdf2png/pdf2png.js index 273fcd971..fad613687 100644 --- a/examples/node/pdf2png/pdf2png.js +++ b/examples/node/pdf2png/pdf2png.js @@ -13,16 +13,16 @@ * limitations under the License. */ -var Canvas = require('canvas'); -var assert = require('assert').strict; -var fs = require('fs'); +var Canvas = require("canvas"); +var assert = require("assert").strict; +var fs = require("fs"); function NodeCanvasFactory() {} NodeCanvasFactory.prototype = { create: function NodeCanvasFactory_create(width, height) { - assert(width > 0 && height > 0, 'Invalid canvas size'); + assert(width > 0 && height > 0, "Invalid canvas size"); var canvas = Canvas.createCanvas(width, height); - var context = canvas.getContext('2d'); + var context = canvas.getContext("2d"); return { canvas: canvas, context: context, @@ -30,14 +30,14 @@ NodeCanvasFactory.prototype = { }, reset: function NodeCanvasFactory_reset(canvasAndContext, width, height) { - assert(canvasAndContext.canvas, 'Canvas is not specified'); - assert(width > 0 && height > 0, 'Invalid canvas size'); + assert(canvasAndContext.canvas, "Canvas is not specified"); + assert(width > 0 && height > 0, "Invalid canvas size"); canvasAndContext.canvas.width = width; canvasAndContext.canvas.height = height; }, destroy: function NodeCanvasFactory_destroy(canvasAndContext) { - assert(canvasAndContext.canvas, 'Canvas is not specified'); + assert(canvasAndContext.canvas, "Canvas is not specified"); // Zeroing the width and height cause Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. @@ -48,46 +48,51 @@ NodeCanvasFactory.prototype = { }, }; -var pdfjsLib = require('pdfjs-dist'); +var pdfjsLib = require("pdfjs-dist"); // Relative path of the PDF file. -var pdfURL = '../../../web/compressed.tracemonkey-pldi-09.pdf'; +var pdfURL = "../../../web/compressed.tracemonkey-pldi-09.pdf"; // Read the PDF file into a typed array so PDF.js can load it. var rawData = new Uint8Array(fs.readFileSync(pdfURL)); // Load the PDF file. var loadingTask = pdfjsLib.getDocument(rawData); -loadingTask.promise.then(function(pdfDocument) { - console.log('# PDF document loaded.'); +loadingTask.promise + .then(function(pdfDocument) { + console.log("# PDF document loaded."); - // Get the first page. - pdfDocument.getPage(1).then(function (page) { - // Render the page on a Node canvas with 100% scale. - var viewport = page.getViewport({ scale: 1.0, }); - var canvasFactory = new NodeCanvasFactory(); - var canvasAndContext = - canvasFactory.create(viewport.width, viewport.height); - var renderContext = { - canvasContext: canvasAndContext.context, - viewport: viewport, - canvasFactory: canvasFactory, - }; + // Get the first page. + pdfDocument.getPage(1).then(function(page) { + // Render the page on a Node canvas with 100% scale. + var viewport = page.getViewport({ scale: 1.0 }); + var canvasFactory = new NodeCanvasFactory(); + var canvasAndContext = canvasFactory.create( + viewport.width, + viewport.height + ); + var renderContext = { + canvasContext: canvasAndContext.context, + viewport: viewport, + canvasFactory: canvasFactory, + }; - var renderTask = page.render(renderContext); - renderTask.promise.then(function() { - // Convert the canvas to an image buffer. - var image = canvasAndContext.canvas.toBuffer(); - fs.writeFile('output.png', image, function (error) { - if (error) { - console.error('Error: ' + error); - } else { - console.log( - 'Finished converting first page of PDF file to a PNG image.'); - } + var renderTask = page.render(renderContext); + renderTask.promise.then(function() { + // Convert the canvas to an image buffer. + var image = canvasAndContext.canvas.toBuffer(); + fs.writeFile("output.png", image, function(error) { + if (error) { + console.error("Error: " + error); + } else { + console.log( + "Finished converting first page of PDF file to a PNG image." + ); + } + }); }); }); + }) + .catch(function(reason) { + console.log(reason); }); -}).catch(function(reason) { - console.log(reason); -}); diff --git a/examples/node/pdf2svg.js b/examples/node/pdf2svg.js index 50860d869..14d6ce494 100644 --- a/examples/node/pdf2svg.js +++ b/examples/node/pdf2svg.js @@ -5,29 +5,29 @@ // Node tool to dump SVG output into a file. // -var fs = require('fs'); -var util = require('util'); -var path = require('path'); -var stream = require('stream'); +var fs = require("fs"); +var util = require("util"); +var path = require("path"); +var stream = require("stream"); // HACK few hacks to let PDF.js be loaded not as a module in global space. -require('./domstubs.js').setStubs(global); +require("./domstubs.js").setStubs(global); // Run `gulp dist-install` to generate 'pdfjs-dist' npm package files. -var pdfjsLib = require('pdfjs-dist'); +var pdfjsLib = require("pdfjs-dist"); // Loading file from file system into typed array -var pdfPath = process.argv[2] || '../../web/compressed.tracemonkey-pldi-09.pdf'; +var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf"; var data = new Uint8Array(fs.readFileSync(pdfPath)); -var outputDirectory = './svgdump'; +var outputDirectory = "./svgdump"; try { // Note: This creates a directory only one level deep. If you want to create // multiple subdirectories on the fly, use the mkdirp module from npm. fs.mkdirSync(outputDirectory); } catch (e) { - if (e.code !== 'EEXIST') { + if (e.code !== "EEXIST") { throw e; } } @@ -35,7 +35,7 @@ try { // Dumps svg outputs to a folder called svgdump function getFilePathForPage(pageNum) { var name = path.basename(pdfPath, path.extname(pdfPath)); - return path.join(outputDirectory, name + '-' + pageNum + '.svg'); + return path.join(outputDirectory, name + "-" + pageNum + ".svg"); } /** @@ -71,9 +71,9 @@ function writeSvgToFile(svgElement, filePath) { }); var writableStream = fs.createWriteStream(filePath); return new Promise(function(resolve, reject) { - readableSvgStream.once('error', reject); - writableStream.once('error', reject); - writableStream.once('finish', resolve); + readableSvgStream.once("error", reject); + writableStream.once("error", reject); + writableStream.once("finish", resolve); readableSvgStream.pipe(writableStream); }).catch(function(err) { readableSvgStream = null; // Explicitly null because of v8 bug 6512. @@ -90,41 +90,48 @@ var loadingTask = pdfjsLib.getDocument({ // processing. nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY, }); -loadingTask.promise.then(function(doc) { - var numPages = doc.numPages; - console.log('# Document Loaded'); - console.log('Number of Pages: ' + numPages); - console.log(); +loadingTask.promise + .then(function(doc) { + var numPages = doc.numPages; + console.log("# Document Loaded"); + console.log("Number of Pages: " + numPages); + console.log(); - var lastPromise = Promise.resolve(); // will be used to chain promises - var loadPage = function (pageNum) { - return doc.getPage(pageNum).then(function (page) { - console.log('# Page ' + pageNum); - var viewport = page.getViewport({ scale: 1.0, }); - console.log('Size: ' + viewport.width + 'x' + viewport.height); - console.log(); + var lastPromise = Promise.resolve(); // will be used to chain promises + var loadPage = function(pageNum) { + return doc.getPage(pageNum).then(function(page) { + console.log("# Page " + pageNum); + var viewport = page.getViewport({ scale: 1.0 }); + console.log("Size: " + viewport.width + "x" + viewport.height); + console.log(); - return page.getOperatorList().then(function (opList) { - var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs); - svgGfx.embedFonts = true; - return svgGfx.getSVG(opList, viewport).then(function (svg) { - return writeSvgToFile(svg, getFilePathForPage(pageNum)) - .then(function () { - console.log('Page: ' + pageNum); - }, function(err) { - console.log('Error: ' + err); - }); + return page.getOperatorList().then(function(opList) { + var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs); + svgGfx.embedFonts = true; + return svgGfx.getSVG(opList, viewport).then(function(svg) { + return writeSvgToFile(svg, getFilePathForPage(pageNum)).then( + function() { + console.log("Page: " + pageNum); + }, + function(err) { + console.log("Error: " + err); + } + ); + }); }); }); - }); - }; + }; - for (var i = 1; i <= numPages; i++) { - lastPromise = lastPromise.then(loadPage.bind(null, i)); - } - return lastPromise; -}).then(function () { - console.log('# End of Document'); -}, function (err) { - console.error('Error: ' + err); -}); + for (var i = 1; i <= numPages; i++) { + lastPromise = lastPromise.then(loadPage.bind(null, i)); + } + return lastPromise; + }) + .then( + function() { + console.log("# End of Document"); + }, + function(err) { + console.error("Error: " + err); + } + ); diff --git a/examples/svgviewer/viewer.js b/examples/svgviewer/viewer.js index 718b143aa..9a32261d3 100644 --- a/examples/svgviewer/viewer.js +++ b/examples/svgviewer/viewer.js @@ -13,26 +13,27 @@ * limitations under the License. */ -'use strict'; +"use strict"; if (!pdfjsLib.getDocument || !pdfjsViewer.PDFViewer) { - alert('Please build the pdfjs-dist library using\n' + - ' `gulp dist-install`'); + alert( + "Please build the pdfjs-dist library using\n" + " `gulp dist-install`" + ); } // The workerSrc property shall be specified. // pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; // Some PDFs need external cmaps. // -var CMAP_URL = '../../node_modules/pdfjs-dist/cmaps/'; +var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; var CMAP_PACKED = true; -var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf'; +var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; -var container = document.getElementById('viewerContainer'); +var container = document.getElementById("viewerContainer"); // (Optionally) enable hyperlinks within PDF files. var pdfLinkService = new pdfjsViewer.PDFLinkService(); @@ -40,14 +41,14 @@ var pdfLinkService = new pdfjsViewer.PDFLinkService(); var pdfViewer = new pdfjsViewer.PDFViewer({ container: container, linkService: pdfLinkService, - renderer: 'svg', + renderer: "svg", textLayerMode: 0, }); pdfLinkService.setViewer(pdfViewer); -document.addEventListener('pagesinit', function () { +document.addEventListener("pagesinit", function() { // We can use pdfViewer now, e.g. let's change default scale. - pdfViewer.currentScaleValue = 'page-width'; + pdfViewer.currentScaleValue = "page-width"; }); // Loading document. diff --git a/examples/text-only/pdf2svg.js b/examples/text-only/pdf2svg.js index 3ce9d6259..51bfd2cd7 100644 --- a/examples/text-only/pdf2svg.js +++ b/examples/text-only/pdf2svg.js @@ -13,34 +13,35 @@ * limitations under the License. */ -var PDF_PATH = '../../web/compressed.tracemonkey-pldi-09.pdf'; +var PDF_PATH = "../../web/compressed.tracemonkey-pldi-09.pdf"; var PAGE_NUMBER = 1; var PAGE_SCALE = 1.5; -var SVG_NS = 'http://www.w3.org/2000/svg'; +var SVG_NS = "http://www.w3.org/2000/svg"; pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../node_modules/pdfjs-dist/build/pdf.worker.js'; + "../../node_modules/pdfjs-dist/build/pdf.worker.js"; function buildSVG(viewport, textContent) { // Building SVG with size of the viewport (for simplicity) - var svg = document.createElementNS(SVG_NS, 'svg:svg'); - svg.setAttribute('width', viewport.width + 'px'); - svg.setAttribute('height', viewport.height + 'px'); + var svg = document.createElementNS(SVG_NS, "svg:svg"); + svg.setAttribute("width", viewport.width + "px"); + svg.setAttribute("height", viewport.height + "px"); // items are transformed to have 1px font size - svg.setAttribute('font-size', 1); + svg.setAttribute("font-size", 1); // processing all items - textContent.items.forEach(function (textItem) { + textContent.items.forEach(function(textItem) { // we have to take in account viewport transform, which includes scale, // rotation and Y-axis flip, and not forgetting to flip text. var tx = pdfjsLib.Util.transform( pdfjsLib.Util.transform(viewport.transform, textItem.transform), - [1, 0, 0, -1, 0, 0]); + [1, 0, 0, -1, 0, 0] + ); var style = textContent.styles[textItem.fontName]; // adding text element - var text = document.createElementNS(SVG_NS, 'svg:text'); - text.setAttribute('transform', 'matrix(' + tx.join(' ') + ')'); - text.setAttribute('font-family', style.fontFamily); + var text = document.createElementNS(SVG_NS, "svg:text"); + text.setAttribute("transform", "matrix(" + tx.join(" ") + ")"); + text.setAttribute("font-family", style.fontFamily); text.textContent = textItem.str; svg.appendChild(text); }); @@ -49,23 +50,25 @@ function buildSVG(viewport, textContent) { function pageLoaded() { // Loading document and page text content - var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH, }); + var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH }); loadingTask.promise.then(function(pdfDocument) { - pdfDocument.getPage(PAGE_NUMBER).then(function (page) { - var viewport = page.getViewport({ scale: PAGE_SCALE, }); - page.getTextContent().then(function (textContent) { + pdfDocument.getPage(PAGE_NUMBER).then(function(page) { + var viewport = page.getViewport({ scale: PAGE_SCALE }); + page.getTextContent().then(function(textContent) { // building SVG and adding that to the DOM var svg = buildSVG(viewport, textContent); - document.getElementById('pageContainer').appendChild(svg); + document.getElementById("pageContainer").appendChild(svg); }); }); }); } -document.addEventListener('DOMContentLoaded', function () { - if (typeof pdfjsLib === 'undefined') { - alert('Built version of PDF.js was not found.\n' + - 'Please run `gulp dist-install`.'); +document.addEventListener("DOMContentLoaded", function() { + if (typeof pdfjsLib === "undefined") { + alert( + "Built version of PDF.js was not found.\n" + + "Please run `gulp dist-install`." + ); return; } pageLoaded(); diff --git a/examples/webpack/main.js b/examples/webpack/main.js index bc21b5f32..053bea8a0 100644 --- a/examples/webpack/main.js +++ b/examples/webpack/main.js @@ -3,31 +3,33 @@ // Hello world example for webpack. -var pdfjsLib = require('pdfjs-dist'); +var pdfjsLib = require("pdfjs-dist"); -var pdfPath = '../learning/helloworld.pdf'; +var pdfPath = "../learning/helloworld.pdf"; // Setting worker path to worker bundle. pdfjsLib.GlobalWorkerOptions.workerSrc = - '../../build/webpack/pdf.worker.bundle.js'; + "../../build/webpack/pdf.worker.bundle.js"; // Loading a document. var loadingTask = pdfjsLib.getDocument(pdfPath); -loadingTask.promise.then(function (pdfDocument) { - // Request a first page - return pdfDocument.getPage(1).then(function (pdfPage) { - // Display page on the existing canvas with 100% scale. - var viewport = pdfPage.getViewport({ scale: 1.0, }); - var canvas = document.getElementById('theCanvas'); - canvas.width = viewport.width; - canvas.height = viewport.height; - var ctx = canvas.getContext('2d'); - var renderTask = pdfPage.render({ - canvasContext: ctx, - viewport: viewport, +loadingTask.promise + .then(function(pdfDocument) { + // Request a first page + return pdfDocument.getPage(1).then(function(pdfPage) { + // Display page on the existing canvas with 100% scale. + var viewport = pdfPage.getViewport({ scale: 1.0 }); + var canvas = document.getElementById("theCanvas"); + canvas.width = viewport.width; + canvas.height = viewport.height; + var ctx = canvas.getContext("2d"); + var renderTask = pdfPage.render({ + canvasContext: ctx, + viewport: viewport, + }); + return renderTask.promise; }); - return renderTask.promise; + }) + .catch(function(reason) { + console.error("Error: " + reason); }); -}).catch(function (reason) { - console.error('Error: ' + reason); -}); diff --git a/examples/webpack/webpack.config.js b/examples/webpack/webpack.config.js index 69ff53edc..4db8758f3 100644 --- a/examples/webpack/webpack.config.js +++ b/examples/webpack/webpack.config.js @@ -1,16 +1,16 @@ -var webpack = require('webpack'); // eslint-disable-line no-unused-vars -var path = require('path'); +var webpack = require("webpack"); // eslint-disable-line no-unused-vars +var path = require("path"); module.exports = { context: __dirname, entry: { - 'main': './main.js', - 'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry', + main: "./main.js", + "pdf.worker": "pdfjs-dist/build/pdf.worker.entry", }, - mode: 'none', + mode: "none", output: { - path: path.join(__dirname, '../../build/webpack'), - publicPath: '../../build/webpack/', - filename: '[name].bundle.js', + path: path.join(__dirname, "../../build/webpack"), + publicPath: "../../build/webpack/", + filename: "[name].bundle.js", }, }; diff --git a/extensions/chromium/contentscript.js b/extensions/chromium/contentscript.js index 3a7d86fde..5680a5b3a 100644 --- a/extensions/chromium/contentscript.js +++ b/extensions/chromium/contentscript.js @@ -14,22 +14,22 @@ See the License for the specific language governing permissions and limitations under the License. */ -'use strict'; +"use strict"; -var VIEWER_URL = chrome.extension.getURL('content/web/viewer.html'); +var VIEWER_URL = chrome.extension.getURL("content/web/viewer.html"); function getViewerURL(pdf_url) { - return VIEWER_URL + '?file=' + encodeURIComponent(pdf_url); + return VIEWER_URL + "?file=" + encodeURIComponent(pdf_url); } -if (CSS.supports('animation', '0s')) { - document.addEventListener('animationstart', onAnimationStart, true); +if (CSS.supports("animation", "0s")) { + document.addEventListener("animationstart", onAnimationStart, true); } else { - document.addEventListener('webkitAnimationStart', onAnimationStart, true); + document.addEventListener("webkitAnimationStart", onAnimationStart, true); } function onAnimationStart(event) { - if (event.animationName === 'pdfjs-detected-object-or-embed') { + if (event.animationName === "pdfjs-detected-object-or-embed") { watchObjectOrEmbed(event.target); } } @@ -40,19 +40,23 @@ function onAnimationStart(event) { // invocations have no effect. function watchObjectOrEmbed(elem) { var mimeType = elem.type; - if (mimeType && mimeType.toLowerCase() !== 'application/pdf') { + if (mimeType && mimeType.toLowerCase() !== "application/pdf") { return; } // - var srcAttribute = 'src' in elem ? 'src' : 'data'; + var srcAttribute = "src" in elem ? "src" : "data"; var path = elem[srcAttribute]; if (!mimeType && !/\.pdf($|[?#])/i.test(path)) { return; } - if (elem.tagName === 'EMBED' && elem.name === 'plugin' && - elem.parentNode === document.body && - elem.parentNode.childElementCount === 1 && elem.src === location.href) { + if ( + elem.tagName === "EMBED" && + elem.name === "plugin" && + elem.parentNode === document.body && + elem.parentNode.childElementCount === 1 && + elem.src === location.href + ) { // This page is most likely Chrome's default page that embeds a PDF file. // The fact that the extension's background page did not intercept and // redirect this PDF request means that this PDF cannot be opened by PDF.js, @@ -62,7 +66,7 @@ function watchObjectOrEmbed(elem) { // Until #4483 is fixed, POST requests should be ignored. return; } - if (elem.tagName === 'EMBED' && elem.src === 'about:blank') { + if (elem.tagName === "EMBED" && elem.src === "about:blank") { // Starting from Chrome 76, internal embeds do not have the original URL, // but "about:blank" instead. // See https://github.com/mozilla/pdf.js/issues/11137 @@ -76,9 +80,9 @@ function watchObjectOrEmbed(elem) { var tagName = elem.tagName.toUpperCase(); var updateEmbedOrObject; - if (tagName === 'EMBED') { + if (tagName === "EMBED") { updateEmbedOrObject = updateEmbedElement; - } else if (tagName === 'OBJECT') { + } else if (tagName === "OBJECT") { updateEmbedOrObject = updateObjectElement; } else { return; @@ -115,7 +119,7 @@ function watchObjectOrEmbed(elem) { // Display the PDF Viewer in an . function updateEmbedElement(elem) { - if (elem.type === 'text/html' && elem.src.lastIndexOf(VIEWER_URL, 0) === 0) { + if (elem.type === "text/html" && elem.src.lastIndexOf(VIEWER_URL, 0) === 0) { // The viewer is already shown. return; } @@ -126,7 +130,7 @@ function updateEmbedElement(elem) { if (parentNode) { parentNode.removeChild(elem); } - elem.type = 'text/html'; + elem.type = "text/html"; elem.src = getEmbeddedViewerURL(elem.src); if (parentNode) { parentNode.insertBefore(elem, nextSibling); @@ -155,21 +159,21 @@ function updateObjectElement(elem) { var iframe = elem.firstElementChild; if (!iframe || !iframe.__inserted_by_pdfjs) { iframe = createFullSizeIframe(); - elem.textContent = ''; + elem.textContent = ""; elem.appendChild(iframe); iframe.__inserted_by_pdfjs = true; } iframe.src = getEmbeddedViewerURL(elem.data); // Some bogus content type that is not handled by any plugin. - elem.type = 'application/not-a-pee-dee-eff-type'; + elem.type = "application/not-a-pee-dee-eff-type"; // Force the to reload and render its fallback content. - elem.data += ''; + elem.data += ""; // Usually the browser renders plugin content in this tag, which is completely // oblivious of styles such as padding, but we insert and render child nodes, // so force padding to be zero to avoid undesired dimension changes. - elem.style.padding = '0'; + elem.style.padding = "0"; // and elements have a "display:inline" style by default. // Despite this property, when a plugin is loaded in the tag, the tag is @@ -180,27 +184,27 @@ function updateObjectElement(elem) { // web pages is respected. // ( behaves as expected with the default display value, but setting it // to display:inline-block doesn't hurt). - elem.style.display = 'inline-block'; + elem.style.display = "inline-block"; } // Create an