Merge pull request #13087 from Snuffleupagus/eslint-examples-no-var

Enable the ESLint `no-var` rule in the `examples/` folder
This commit is contained in:
Tim van der Meij 2021-03-13 13:04:00 +01:00 committed by GitHub
commit 1abdcbaab5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 212 additions and 207 deletions

View File

@ -8,4 +8,9 @@
"pdfjsLib": false, "pdfjsLib": false,
"pdfjsViewer": false, "pdfjsViewer": false,
}, },
"rules": {
// ECMAScript 6
"no-var": "error",
},
} }

View File

@ -1,12 +1,12 @@
var gulp = require("gulp"); const gulp = require("gulp");
var browserify = require("browserify"); const browserify = require("browserify");
var streamify = require("gulp-streamify"); const streamify = require("gulp-streamify");
var rename = require("gulp-rename"); const rename = require("gulp-rename");
var uglify = require("gulp-uglify"); const uglify = require("gulp-uglify");
var source = require("vinyl-source-stream"); const source = require("vinyl-source-stream");
var OUTPUT_PATH = "../../build/browserify"; const OUTPUT_PATH = "../../build/browserify";
var TMP_FILE_PREFIX = "../../build/browserify_"; const TMP_FILE_PREFIX = "../../build/browserify_";
gulp.task("build-bundle", function () { gulp.task("build-bundle", function () {
return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" }) return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" })
@ -20,7 +20,7 @@ gulp.task("build-bundle", function () {
gulp.task("build-worker", function () { gulp.task("build-worker", function () {
// We can create our own viewer (see worker.js) or use already defined one. // We can create our own viewer (see worker.js) or use already defined one.
var workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry"); const workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry");
return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" }) return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" })
.bundle() .bundle()
.pipe(source(TMP_FILE_PREFIX + "worker.tmp")) .pipe(source(TMP_FILE_PREFIX + "worker.tmp"))

View File

@ -3,27 +3,27 @@
// Hello world example for browserify. // Hello world example for browserify.
var pdfjsLib = require("pdfjs-dist"); const pdfjsLib = require("pdfjs-dist");
var pdfPath = "../learning/helloworld.pdf"; const pdfPath = "../learning/helloworld.pdf";
// Setting worker path to worker bundle. // Setting worker path to worker bundle.
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsLib.GlobalWorkerOptions.workerSrc =
"../../build/browserify/pdf.worker.bundle.js"; "../../build/browserify/pdf.worker.bundle.js";
// Loading a document. // Loading a document.
var loadingTask = pdfjsLib.getDocument(pdfPath); const loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise loadingTask.promise
.then(function (pdfDocument) { .then(function (pdfDocument) {
// Request a first page // Request a first page
return pdfDocument.getPage(1).then(function (pdfPage) { return pdfDocument.getPage(1).then(function (pdfPage) {
// Display page on the existing canvas with 100% scale. // Display page on the existing canvas with 100% scale.
var viewport = pdfPage.getViewport({ scale: 1.0 }); const viewport = pdfPage.getViewport({ scale: 1.0 });
var canvas = document.getElementById("theCanvas"); const canvas = document.getElementById("theCanvas");
canvas.width = viewport.width; canvas.width = viewport.width;
canvas.height = viewport.height; canvas.height = viewport.height;
var ctx = canvas.getContext("2d"); const ctx = canvas.getContext("2d");
var renderTask = pdfPage.render({ const renderTask = pdfPage.render({
canvasContext: ctx, canvasContext: ctx,
viewport, viewport,
}); });

View File

@ -27,19 +27,19 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Some PDFs need external cmaps. // Some PDFs need external cmaps.
// //
var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; const DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf";
var PAGE_TO_VIEW = 1; const PAGE_TO_VIEW = 1;
var SCALE = 1.0; const SCALE = 1.0;
var container = document.getElementById("pageContainer"); const container = document.getElementById("pageContainer");
var eventBus = new pdfjsViewer.EventBus(); const eventBus = new pdfjsViewer.EventBus();
// Loading document. // Loading document.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
url: DEFAULT_URL, url: DEFAULT_URL,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
@ -48,7 +48,7 @@ loadingTask.promise.then(function (pdfDocument) {
// Document loaded, retrieving the page. // 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. // Creating the page view with default parameters.
var pdfPageView = new pdfjsViewer.PDFPageView({ const pdfPageView = new pdfjsViewer.PDFPageView({
container, container,
id: PAGE_TO_VIEW, id: PAGE_TO_VIEW,
scale: SCALE, scale: SCALE,

View File

@ -27,40 +27,40 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Some PDFs need external cmaps. // Some PDFs need external cmaps.
// //
var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; const DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf";
// To test the AcroForm and/or scripting functionality, try e.g. this file: // To test the AcroForm and/or scripting functionality, try e.g. this file:
// var DEFAULT_URL = "../../test/pdfs/160F-2019.pdf"; // var DEFAULT_URL = "../../test/pdfs/160F-2019.pdf";
var SEARCH_FOR = ""; // try 'Mozilla'; const SEARCH_FOR = ""; // try 'Mozilla';
// For scripting support, note also `enableScripting` below. // For scripting support, note also `enableScripting` below.
var SANDBOX_BUNDLE_SRC = "../../node_modules/pdfjs-dist/build/pdf.sandbox.js"; const SANDBOX_BUNDLE_SRC = "../../node_modules/pdfjs-dist/build/pdf.sandbox.js";
var container = document.getElementById("viewerContainer"); const container = document.getElementById("viewerContainer");
var eventBus = new pdfjsViewer.EventBus(); const eventBus = new pdfjsViewer.EventBus();
// (Optionally) enable hyperlinks within PDF files. // (Optionally) enable hyperlinks within PDF files.
var pdfLinkService = new pdfjsViewer.PDFLinkService({ const pdfLinkService = new pdfjsViewer.PDFLinkService({
eventBus, eventBus,
}); });
// (Optionally) enable find controller. // (Optionally) enable find controller.
var pdfFindController = new pdfjsViewer.PDFFindController({ const pdfFindController = new pdfjsViewer.PDFFindController({
eventBus, eventBus,
linkService: pdfLinkService, linkService: pdfLinkService,
}); });
// (Optionally) enable scripting support. // (Optionally) enable scripting support.
var pdfScriptingManager = new pdfjsViewer.PDFScriptingManager({ const pdfScriptingManager = new pdfjsViewer.PDFScriptingManager({
eventBus, eventBus,
sandboxBundleSrc: SANDBOX_BUNDLE_SRC, sandboxBundleSrc: SANDBOX_BUNDLE_SRC,
}); });
var pdfViewer = new pdfjsViewer.PDFViewer({ const pdfViewer = new pdfjsViewer.PDFViewer({
container, container,
eventBus, eventBus,
linkService: pdfLinkService, linkService: pdfLinkService,
@ -82,7 +82,7 @@ eventBus.on("pagesinit", function () {
}); });
// Loading document. // Loading document.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
url: DEFAULT_URL, url: DEFAULT_URL,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,

View File

@ -27,40 +27,40 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Some PDFs need external cmaps. // Some PDFs need external cmaps.
// //
var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; const DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf";
// To test the AcroForm and/or scripting functionality, try e.g. this file: // To test the AcroForm and/or scripting functionality, try e.g. this file:
// var DEFAULT_URL = "../../test/pdfs/160F-2019.pdf"; // var DEFAULT_URL = "../../test/pdfs/160F-2019.pdf";
var SEARCH_FOR = ""; // try 'Mozilla'; const SEARCH_FOR = ""; // try 'Mozilla';
// For scripting support, note also `enableScripting` below. // For scripting support, note also `enableScripting` below.
var SANDBOX_BUNDLE_SRC = "../../node_modules/pdfjs-dist/build/pdf.sandbox.js"; const SANDBOX_BUNDLE_SRC = "../../node_modules/pdfjs-dist/build/pdf.sandbox.js";
var container = document.getElementById("viewerContainer"); const container = document.getElementById("viewerContainer");
var eventBus = new pdfjsViewer.EventBus(); const eventBus = new pdfjsViewer.EventBus();
// (Optionally) enable hyperlinks within PDF files. // (Optionally) enable hyperlinks within PDF files.
var pdfLinkService = new pdfjsViewer.PDFLinkService({ const pdfLinkService = new pdfjsViewer.PDFLinkService({
eventBus, eventBus,
}); });
// (Optionally) enable find controller. // (Optionally) enable find controller.
var pdfFindController = new pdfjsViewer.PDFFindController({ const pdfFindController = new pdfjsViewer.PDFFindController({
eventBus, eventBus,
linkService: pdfLinkService, linkService: pdfLinkService,
}); });
// (Optionally) enable scripting support. // (Optionally) enable scripting support.
var pdfScriptingManager = new pdfjsViewer.PDFScriptingManager({ const pdfScriptingManager = new pdfjsViewer.PDFScriptingManager({
eventBus, eventBus,
sandboxBundleSrc: SANDBOX_BUNDLE_SRC, sandboxBundleSrc: SANDBOX_BUNDLE_SRC,
}); });
var pdfSinglePageViewer = new pdfjsViewer.PDFSinglePageViewer({ const pdfSinglePageViewer = new pdfjsViewer.PDFSinglePageViewer({
container, container,
eventBus, eventBus,
linkService: pdfLinkService, linkService: pdfLinkService,
@ -82,7 +82,7 @@ eventBus.on("pagesinit", function () {
}); });
// Loading document. // Loading document.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
url: DEFAULT_URL, url: DEFAULT_URL,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,

View File

@ -20,15 +20,15 @@ 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"; const JPEG_IMAGE = "fish.jpg";
var jpegCanvas = document.getElementById("jpegCanvas"); const jpegCanvas = document.getElementById("jpegCanvas");
var jpegCtx = jpegCanvas.getContext("2d"); const jpegCtx = jpegCanvas.getContext("2d");
// Load the image data, and convert it to a Uint8Array. // Load the image data, and convert it to a Uint8Array.
// //
var nonBinaryRequest = false; let nonBinaryRequest = false;
var request = new XMLHttpRequest(); const request = new XMLHttpRequest();
request.open("GET", JPEG_IMAGE, false); request.open("GET", JPEG_IMAGE, false);
try { try {
request.responseType = "arraybuffer"; request.responseType = "arraybuffer";
@ -41,12 +41,12 @@ if (nonBinaryRequest && request.overrideMimeType) {
} }
request.send(null); request.send(null);
var typedArrayImage; let typedArrayImage;
if (nonBinaryRequest) { if (nonBinaryRequest) {
var str = request.responseText, const str = request.responseText,
length = str.length; length = str.length;
var bytes = new Uint8Array(length); const bytes = new Uint8Array(length);
for (var i = 0; i < length; ++i) { for (let i = 0; i < length; ++i) {
bytes[i] = str.charCodeAt(i) & 0xff; bytes[i] = str.charCodeAt(i) & 0xff;
} }
typedArrayImage = bytes; typedArrayImage = bytes;
@ -56,12 +56,12 @@ if (nonBinaryRequest) {
// Parse the image data using `JpegImage`. // Parse the image data using `JpegImage`.
// //
var jpegImage = new pdfjsImageDecoders.JpegImage(); const jpegImage = new pdfjsImageDecoders.JpegImage();
jpegImage.parse(typedArrayImage); jpegImage.parse(typedArrayImage);
var width = jpegImage.width, const width = jpegImage.width,
height = jpegImage.height; height = jpegImage.height;
var jpegData = jpegImage.getData({ const jpegData = jpegImage.getData({
width, width,
height, height,
forceRGB: true, forceRGB: true,
@ -69,9 +69,9 @@ var jpegData = jpegImage.getData({
// Render the JPEG image on a <canvas>. // Render the JPEG image on a <canvas>.
// //
var imageData = jpegCtx.createImageData(width, height); const imageData = jpegCtx.createImageData(width, height);
var imageBytes = imageData.data; const imageBytes = imageData.data;
for (var j = 0, k = 0, jj = width * height * 4; j < jj; ) { for (let j = 0, k = 0, jj = width * height * 4; j < jj; ) {
imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++];
imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++];
imageBytes[j++] = jpegData[k++]; imageBytes[j++] = jpegData[k++];

View File

@ -20,22 +20,22 @@ 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; const USE_ONLY_CSS_ZOOM = true;
var TEXT_LAYER_MODE = 0; // DISABLE const TEXT_LAYER_MODE = 0; // DISABLE
var MAX_IMAGE_SIZE = 1024 * 1024; const MAX_IMAGE_SIZE = 1024 * 1024;
var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
pdfjsLib.GlobalWorkerOptions.workerSrc = 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"; const DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf";
var DEFAULT_SCALE_DELTA = 1.1; const DEFAULT_SCALE_DELTA = 1.1;
var MIN_SCALE = 0.25; const MIN_SCALE = 0.25;
var MAX_SCALE = 10.0; const MAX_SCALE = 10.0;
var DEFAULT_SCALE_VALUE = "auto"; const DEFAULT_SCALE_VALUE = "auto";
var PDFViewerApplication = { const PDFViewerApplication = {
pdfLoadingTask: null, pdfLoadingTask: null,
pdfDocument: null, pdfDocument: null,
pdfViewer: null, pdfViewer: null,
@ -59,12 +59,12 @@ var PDFViewerApplication = {
); );
} }
var url = params.url; const url = params.url;
var self = this; const self = this;
this.setTitleUsingUrl(url); this.setTitleUsingUrl(url);
// Loading document. // Loading document.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
url, url,
maxImageSize: MAX_IMAGE_SIZE, maxImageSize: MAX_IMAGE_SIZE,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
@ -88,9 +88,9 @@ var PDFViewerApplication = {
self.setTitleUsingMetadata(pdfDocument); self.setTitleUsingMetadata(pdfDocument);
}, },
function (exception) { function (exception) {
var message = exception && exception.message; const message = exception && exception.message;
var l10n = self.l10n; const l10n = self.l10n;
var loadingErrorMessage; let loadingErrorMessage;
if (exception instanceof pdfjsLib.InvalidPDFException) { if (exception instanceof pdfjsLib.InvalidPDFException) {
// change error message also for other builds // change error message also for other builds
@ -134,14 +134,14 @@ var PDFViewerApplication = {
* destruction is completed. * destruction is completed.
*/ */
close() { close() {
var errorWrapper = document.getElementById("errorWrapper"); const errorWrapper = document.getElementById("errorWrapper");
errorWrapper.hidden = true; errorWrapper.hidden = true;
if (!this.pdfLoadingTask) { if (!this.pdfLoadingTask) {
return Promise.resolve(); return Promise.resolve();
} }
var promise = this.pdfLoadingTask.destroy(); const promise = this.pdfLoadingTask.destroy();
this.pdfLoadingTask = null; this.pdfLoadingTask = null;
if (this.pdfDocument) { if (this.pdfDocument) {
@ -159,14 +159,14 @@ var PDFViewerApplication = {
}, },
get loadingBar() { get loadingBar() {
var bar = new pdfjsViewer.ProgressBar("#loadingBar", {}); const bar = new pdfjsViewer.ProgressBar("#loadingBar", {});
return pdfjsLib.shadow(this, "loadingBar", bar); return pdfjsLib.shadow(this, "loadingBar", bar);
}, },
setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) { setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
this.url = url; this.url = url;
var title = pdfjsLib.getFilenameFromUrl(url) || url; let title = pdfjsLib.getFilenameFromUrl(url) || url;
try { try {
title = decodeURIComponent(title); title = decodeURIComponent(title);
} catch (e) { } catch (e) {
@ -177,9 +177,9 @@ var PDFViewerApplication = {
}, },
setTitleUsingMetadata(pdfDocument) { setTitleUsingMetadata(pdfDocument) {
var self = this; const self = this;
pdfDocument.getMetadata().then(function (data) { pdfDocument.getMetadata().then(function (data) {
var info = data.info, const info = data.info,
metadata = data.metadata; metadata = data.metadata;
self.documentInfo = info; self.documentInfo = info;
self.metadata = metadata; self.metadata = metadata;
@ -200,9 +200,9 @@ var PDFViewerApplication = {
")" ")"
); );
var pdfTitle; let pdfTitle;
if (metadata && metadata.has("dc:title")) { if (metadata && metadata.has("dc:title")) {
var title = metadata.get("dc:title"); const title = metadata.get("dc:title");
// Ghostscript sometimes returns 'Untitled', so prevent setting the // Ghostscript sometimes returns 'Untitled', so prevent setting the
// title to 'Untitled. // title to 'Untitled.
if (title !== "Untitled") { if (title !== "Untitled") {
@ -226,8 +226,8 @@ var PDFViewerApplication = {
}, },
error: function pdfViewError(message, moreInfo) { error: function pdfViewError(message, moreInfo) {
var l10n = this.l10n; const l10n = this.l10n;
var moreInfoText = [ const moreInfoText = [
l10n.get( l10n.get(
"error_version_info", "error_version_info",
{ version: pdfjsLib.version || "?", build: pdfjsLib.build || "?" }, { version: pdfjsLib.version || "?", build: pdfjsLib.build || "?" },
@ -269,20 +269,20 @@ var PDFViewerApplication = {
} }
} }
var errorWrapper = document.getElementById("errorWrapper"); const errorWrapper = document.getElementById("errorWrapper");
errorWrapper.hidden = false; errorWrapper.hidden = false;
var errorMessage = document.getElementById("errorMessage"); const errorMessage = document.getElementById("errorMessage");
errorMessage.textContent = message; errorMessage.textContent = message;
var closeButton = document.getElementById("errorClose"); const closeButton = document.getElementById("errorClose");
closeButton.onclick = function () { closeButton.onclick = function () {
errorWrapper.hidden = true; errorWrapper.hidden = true;
}; };
var errorMoreInfo = document.getElementById("errorMoreInfo"); const errorMoreInfo = document.getElementById("errorMoreInfo");
var moreInfoButton = document.getElementById("errorShowMore"); const moreInfoButton = document.getElementById("errorShowMore");
var lessInfoButton = document.getElementById("errorShowLess"); const lessInfoButton = document.getElementById("errorShowLess");
moreInfoButton.onclick = function () { moreInfoButton.onclick = function () {
errorMoreInfo.hidden = false; errorMoreInfo.hidden = false;
moreInfoButton.hidden = true; moreInfoButton.hidden = true;
@ -302,7 +302,7 @@ var PDFViewerApplication = {
}, },
progress: function pdfViewProgress(level) { progress: function pdfViewProgress(level) {
var percent = Math.round(level * 100); const percent = Math.round(level * 100);
// Updating the bar if value increases. // Updating the bar if value increases.
if (percent > this.loadingBar.percent || isNaN(percent)) { if (percent > this.loadingBar.percent || isNaN(percent)) {
this.loadingBar.percent = percent; this.loadingBar.percent = percent;
@ -322,7 +322,7 @@ var PDFViewerApplication = {
}, },
zoomIn: function pdfViewZoomIn(ticks) { zoomIn: function pdfViewZoomIn(ticks) {
var newScale = this.pdfViewer.currentScale; let newScale = this.pdfViewer.currentScale;
do { do {
newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2); newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
newScale = Math.ceil(newScale * 10) / 10; newScale = Math.ceil(newScale * 10) / 10;
@ -332,7 +332,7 @@ var PDFViewerApplication = {
}, },
zoomOut: function pdfViewZoomOut(ticks) { zoomOut: function pdfViewZoomOut(ticks) {
var newScale = this.pdfViewer.currentScale; let newScale = this.pdfViewer.currentScale;
do { do {
newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2); newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
newScale = Math.floor(newScale * 10) / 10; newScale = Math.floor(newScale * 10) / 10;
@ -342,18 +342,18 @@ var PDFViewerApplication = {
}, },
initUI: function pdfViewInitUI() { initUI: function pdfViewInitUI() {
var eventBus = new pdfjsViewer.EventBus(); const eventBus = new pdfjsViewer.EventBus();
this.eventBus = eventBus; this.eventBus = eventBus;
var linkService = new pdfjsViewer.PDFLinkService({ const linkService = new pdfjsViewer.PDFLinkService({
eventBus, eventBus,
}); });
this.pdfLinkService = linkService; this.pdfLinkService = linkService;
this.l10n = pdfjsViewer.NullL10n; this.l10n = pdfjsViewer.NullL10n;
var container = document.getElementById("viewerContainer"); const container = document.getElementById("viewerContainer");
var pdfViewer = new pdfjsViewer.PDFViewer({ const pdfViewer = new pdfjsViewer.PDFViewer({
container, container,
eventBus, eventBus,
linkService, linkService,
@ -413,8 +413,8 @@ var PDFViewerApplication = {
eventBus.on( eventBus.on(
"pagechanging", "pagechanging",
function (evt) { function (evt) {
var page = evt.pageNumber; const page = evt.pageNumber;
var numPages = PDFViewerApplication.pagesCount; const numPages = PDFViewerApplication.pagesCount;
document.getElementById("pageNumber").value = page; document.getElementById("pageNumber").value = page;
document.getElementById("previous").disabled = page <= 1; document.getElementById("previous").disabled = page <= 1;
@ -425,6 +425,8 @@ var PDFViewerApplication = {
}, },
}; };
window.PDFViewerApplication = PDFViewerApplication;
document.addEventListener( document.addEventListener(
"DOMContentLoaded", "DOMContentLoaded",
function () { function () {
@ -433,18 +435,14 @@ document.addEventListener(
true true
); );
(function animationStartedClosure() { // The offsetParent is not set until the PDF.js iframe or object is visible;
// The offsetParent is not set until the PDF.js iframe or object is visible. // waiting for first animation.
// Waiting for first animation. const animationStarted = new Promise(function (resolve) {
PDFViewerApplication.animationStartedPromise = new Promise(function ( window.requestAnimationFrame(resolve);
resolve });
) {
window.requestAnimationFrame(resolve);
});
})();
// We need to delay opening until all HTML is loaded. // We need to delay opening until all HTML is loaded.
PDFViewerApplication.animationStartedPromise.then(function () { animationStarted.then(function () {
PDFViewerApplication.open({ PDFViewerApplication.open({
url: DEFAULT_URL, url: DEFAULT_URL,
}); });

View File

@ -2,7 +2,7 @@
* http://creativecommons.org/publicdomain/zero/1.0/ */ * http://creativecommons.org/publicdomain/zero/1.0/ */
function xmlEncode(s) { function xmlEncode(s) {
var i = 0, let i = 0,
ch; ch;
s = String(s); s = String(s);
while ( while (
@ -19,7 +19,7 @@ function xmlEncode(s) {
if (i >= s.length) { if (i >= s.length) {
return s; return s;
} }
var buf = s.substring(0, i); let buf = s.substring(0, i);
while (i < s.length) { while (i < s.length) {
ch = s[i++]; ch = s[i++];
switch (ch) { switch (ch) {
@ -82,8 +82,8 @@ DOMElement.prototype = {
// Assuming that there is only one matching attribute for a given name, // Assuming that there is only one matching attribute for a given name,
// across all namespaces. // across all namespaces.
if (NS) { if (NS) {
var suffix = ":" + name; const suffix = ":" + name;
for (var fullName in this.attributes) { for (const fullName in this.attributes) {
if (fullName.slice(-suffix.length) === suffix) { if (fullName.slice(-suffix.length) === suffix) {
return this.attributes[fullName]; return this.attributes[fullName];
} }
@ -103,7 +103,7 @@ DOMElement.prototype = {
}, },
appendChild: function DOMElement_appendChild(element) { appendChild: function DOMElement_appendChild(element) {
var childNodes = this.childNodes; const childNodes = this.childNodes;
if (!childNodes.includes(element)) { if (!childNodes.includes(element)) {
childNodes.push(element); childNodes.push(element);
} }
@ -114,7 +114,7 @@ DOMElement.prototype = {
}, },
cloneNode: function DOMElement_cloneNode() { cloneNode: function DOMElement_cloneNode() {
var newNode = new DOMElement(this.nodeName); const newNode = new DOMElement(this.nodeName);
newNode.childNodes = this.childNodes; newNode.childNodes = this.childNodes;
newNode.attributes = this.attributes; newNode.attributes = this.attributes;
newNode.textContent = this.textContent; newNode.textContent = this.textContent;
@ -125,9 +125,9 @@ DOMElement.prototype = {
// getSerializer because that allows you to process the chunks as they come // getSerializer because that allows you to process the chunks as they come
// instead of requiring the whole image to fit in memory. // instead of requiring the whole image to fit in memory.
toString: function DOMElement_toString() { toString: function DOMElement_toString() {
var buf = []; const buf = [];
var serializer = this.getSerializer(); const serializer = this.getSerializer();
var chunk; let chunk;
while ((chunk = serializer.getNext()) !== null) { while ((chunk = serializer.getNext()) !== null) {
buf.push(chunk); buf.push(chunk);
} }
@ -153,7 +153,7 @@ DOMElementSerializer.prototype = {
* @returns {string|null} null if the element has fully been serialized. * @returns {string|null} null if the element has fully been serialized.
*/ */
getNext: function DOMElementSerializer_getNext() { getNext: function DOMElementSerializer_getNext() {
var node = this._node; const node = this._node;
switch (this._state) { switch (this._state) {
case 0: // Start opening tag. case 0: // Start opening tag.
++this._state; ++this._state;
@ -174,7 +174,7 @@ DOMElementSerializer.prototype = {
/* falls through */ /* falls through */
case 3: // Serialize any attributes and end opening tag. case 3: // Serialize any attributes and end opening tag.
if (this._loopIndex < this._attributeKeys.length) { if (this._loopIndex < this._attributeKeys.length) {
var name = this._attributeKeys[this._loopIndex++]; const name = this._attributeKeys[this._loopIndex++];
return " " + name + '="' + xmlEncode(node.attributes[name]) + '"'; return " " + name + '="' + xmlEncode(node.attributes[name]) + '"';
} }
++this._state; ++this._state;
@ -188,13 +188,13 @@ DOMElementSerializer.prototype = {
this._loopIndex = 0; this._loopIndex = 0;
/* falls through */ /* falls through */
case 5: // Serialize child nodes (only for non-tspan/style elements). case 5: // Serialize child nodes (only for non-tspan/style elements).
var value;
while (true) { while (true) {
value = this._childSerializer && this._childSerializer.getNext(); const value =
this._childSerializer && this._childSerializer.getNext();
if (value !== null) { if (value !== null) {
return value; return value;
} }
var nextChild = node.childNodes[this._loopIndex++]; const nextChild = node.childNodes[this._loopIndex++];
if (nextChild) { if (nextChild) {
this._childSerializer = new DOMElementSerializer(nextChild); this._childSerializer = new DOMElementSerializer(nextChild);
} else { } else {
@ -227,7 +227,7 @@ const document = {
}, },
createElementNS(NS, element) { createElementNS(NS, element) {
var elObject = new DOMElement(element); const elObject = new DOMElement(element);
return elObject; return elObject;
}, },
@ -262,7 +262,7 @@ Image.prototype = {
exports.document = document; exports.document = document;
exports.Image = Image; exports.Image = Image;
var exported_symbols = Object.keys(exports); const exported_symbols = Object.keys(exports);
exports.setStubs = function (namespace) { exports.setStubs = function (namespace) {
exported_symbols.forEach(function (key) { exported_symbols.forEach(function (key) {

View File

@ -8,22 +8,23 @@
// //
// Run `gulp dist-install` to generate 'pdfjs-dist' npm package files. // Run `gulp dist-install` to generate 'pdfjs-dist' npm package files.
var pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js"); const pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");
// Loading file from file system into typed array // Loading file from file system into typed array
var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf"; const pdfPath =
process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";
// Will be using promises to load document, pages and misc data instead of // Will be using promises to load document, pages and misc data instead of
// callback. // callback.
var loadingTask = pdfjsLib.getDocument(pdfPath); const loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise loadingTask.promise
.then(function (doc) { .then(function (doc) {
var numPages = doc.numPages; const numPages = doc.numPages;
console.log("# Document Loaded"); console.log("# Document Loaded");
console.log("Number of Pages: " + numPages); console.log("Number of Pages: " + numPages);
console.log(); console.log();
var lastPromise; // will be used to chain promises let lastPromise; // will be used to chain promises
lastPromise = doc.getMetadata().then(function (data) { lastPromise = doc.getMetadata().then(function (data) {
console.log("# Metadata Is Loaded"); console.log("# Metadata Is Loaded");
console.log("## Info"); console.log("## Info");
@ -36,10 +37,10 @@ loadingTask.promise
} }
}); });
var loadPage = function (pageNum) { const loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function (page) { return doc.getPage(pageNum).then(function (page) {
console.log("# Page " + pageNum); console.log("# Page " + pageNum);
var viewport = page.getViewport({ scale: 1.0 }); const viewport = page.getViewport({ scale: 1.0 });
console.log("Size: " + viewport.width + "x" + viewport.height); console.log("Size: " + viewport.width + "x" + viewport.height);
console.log(); console.log();
return page return page
@ -47,7 +48,7 @@ loadingTask.promise
.then(function (content) { .then(function (content) {
// Content contains lots of information about the text layout and // Content contains lots of information about the text layout and
// styles, but we need only strings at the moment // styles, but we need only strings at the moment
var strings = content.items.map(function (item) { const strings = content.items.map(function (item) {
return item.str; return item.str;
}); });
console.log("## Text Content"); console.log("## Text Content");
@ -60,7 +61,7 @@ loadingTask.promise
}; };
// Loading of the first page will wait on metadata and subsequent loadings // Loading of the first page will wait on metadata and subsequent loadings
// will wait on the previous pages. // will wait on the previous pages.
for (var i = 1; i <= numPages; i++) { for (let i = 1; i <= numPages; i++) {
lastPromise = lastPromise.then(loadPage.bind(null, i)); lastPromise = lastPromise.then(loadPage.bind(null, i));
} }
return lastPromise; return lastPromise;

View File

@ -13,16 +13,16 @@
* limitations under the License. * limitations under the License.
*/ */
var Canvas = require("canvas"); const Canvas = require("canvas");
var assert = require("assert").strict; const assert = require("assert").strict;
var fs = require("fs"); const fs = require("fs");
function NodeCanvasFactory() {} function NodeCanvasFactory() {}
NodeCanvasFactory.prototype = { NodeCanvasFactory.prototype = {
create: function NodeCanvasFactory_create(width, height) { 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); const canvas = Canvas.createCanvas(width, height);
var context = canvas.getContext("2d"); const context = canvas.getContext("2d");
return { return {
canvas, canvas,
context, context,
@ -48,19 +48,19 @@ NodeCanvasFactory.prototype = {
}, },
}; };
var pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js"); const pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");
// Some PDFs need external cmaps. // Some PDFs need external cmaps.
var CMAP_URL = "../../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
// Loading file from file system into typed array. // Loading file from file system into typed array.
var pdfPath = const pdfPath =
process.argv[2] || "../../../web/compressed.tracemonkey-pldi-09.pdf"; process.argv[2] || "../../../web/compressed.tracemonkey-pldi-09.pdf";
var data = new Uint8Array(fs.readFileSync(pdfPath)); const data = new Uint8Array(fs.readFileSync(pdfPath));
// Load the PDF file. // Load the PDF file.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
data, data,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
@ -72,22 +72,22 @@ loadingTask.promise
// Get the first page. // Get the first page.
pdfDocument.getPage(1).then(function (page) { pdfDocument.getPage(1).then(function (page) {
// Render the page on a Node canvas with 100% scale. // Render the page on a Node canvas with 100% scale.
var viewport = page.getViewport({ scale: 1.0 }); const viewport = page.getViewport({ scale: 1.0 });
var canvasFactory = new NodeCanvasFactory(); const canvasFactory = new NodeCanvasFactory();
var canvasAndContext = canvasFactory.create( const canvasAndContext = canvasFactory.create(
viewport.width, viewport.width,
viewport.height viewport.height
); );
var renderContext = { const renderContext = {
canvasContext: canvasAndContext.context, canvasContext: canvasAndContext.context,
viewport, viewport,
canvasFactory, canvasFactory,
}; };
var renderTask = page.render(renderContext); const renderTask = page.render(renderContext);
renderTask.promise.then(function () { renderTask.promise.then(function () {
// Convert the canvas to an image buffer. // Convert the canvas to an image buffer.
var image = canvasAndContext.canvas.toBuffer(); const image = canvasAndContext.canvas.toBuffer();
fs.writeFile("output.png", image, function (error) { fs.writeFile("output.png", image, function (error) {
if (error) { if (error) {
console.error("Error: " + error); console.error("Error: " + error);

View File

@ -5,26 +5,27 @@
// Node tool to dump SVG output into a file. // Node tool to dump SVG output into a file.
// //
var fs = require("fs"); const fs = require("fs");
var util = require("util"); const util = require("util");
var path = require("path"); const path = require("path");
var stream = require("stream"); const stream = require("stream");
// HACK few hacks to let PDF.js be loaded not as a module in global space. // 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. // Run `gulp dist-install` to generate 'pdfjs-dist' npm package files.
var pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js"); const pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");
// Some PDFs need external cmaps. // Some PDFs need external cmaps.
var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
// Loading file from file system into typed array // Loading file from file system into typed array
var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf"; const pdfPath =
var data = new Uint8Array(fs.readFileSync(pdfPath)); process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";
const data = new Uint8Array(fs.readFileSync(pdfPath));
var outputDirectory = "./svgdump"; const outputDirectory = "./svgdump";
try { try {
// Note: This creates a directory only one level deep. If you want to create // Note: This creates a directory only one level deep. If you want to create
@ -38,7 +39,7 @@ try {
// Dumps svg outputs to a folder called svgdump // Dumps svg outputs to a folder called svgdump
function getFilePathForPage(pageNum) { function getFilePathForPage(pageNum) {
var name = path.basename(pdfPath, path.extname(pdfPath)); const name = path.basename(pdfPath, path.extname(pdfPath));
return path.join(outputDirectory, name + "-" + pageNum + ".svg"); return path.join(outputDirectory, name + "-" + pageNum + ".svg");
} }
@ -59,7 +60,7 @@ function ReadableSVGStream(options) {
util.inherits(ReadableSVGStream, stream.Readable); util.inherits(ReadableSVGStream, stream.Readable);
// Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1 // Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1
ReadableSVGStream.prototype._read = function () { ReadableSVGStream.prototype._read = function () {
var chunk; let chunk;
while ((chunk = this.serializer.getNext()) !== null) { while ((chunk = this.serializer.getNext()) !== null) {
if (!this.push(chunk)) { if (!this.push(chunk)) {
return; return;
@ -70,10 +71,10 @@ ReadableSVGStream.prototype._read = function () {
// Streams the SVG element to the given file path. // Streams the SVG element to the given file path.
function writeSvgToFile(svgElement, filePath) { function writeSvgToFile(svgElement, filePath) {
var readableSvgStream = new ReadableSVGStream({ let readableSvgStream = new ReadableSVGStream({
svgElement, svgElement,
}); });
var writableStream = fs.createWriteStream(filePath); const writableStream = fs.createWriteStream(filePath);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
readableSvgStream.once("error", reject); readableSvgStream.once("error", reject);
writableStream.once("error", reject); writableStream.once("error", reject);
@ -88,7 +89,7 @@ function writeSvgToFile(svgElement, filePath) {
// Will be using promises to load document, pages and misc data instead of // Will be using promises to load document, pages and misc data instead of
// callback. // callback.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
data, data,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
@ -96,21 +97,21 @@ var loadingTask = pdfjsLib.getDocument({
}); });
loadingTask.promise loadingTask.promise
.then(function (doc) { .then(function (doc) {
var numPages = doc.numPages; const numPages = doc.numPages;
console.log("# Document Loaded"); console.log("# Document Loaded");
console.log("Number of Pages: " + numPages); console.log("Number of Pages: " + numPages);
console.log(); console.log();
var lastPromise = Promise.resolve(); // will be used to chain promises let lastPromise = Promise.resolve(); // will be used to chain promises
var loadPage = function (pageNum) { const loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function (page) { return doc.getPage(pageNum).then(function (page) {
console.log("# Page " + pageNum); console.log("# Page " + pageNum);
var viewport = page.getViewport({ scale: 1.0 }); const viewport = page.getViewport({ scale: 1.0 });
console.log("Size: " + viewport.width + "x" + viewport.height); console.log("Size: " + viewport.width + "x" + viewport.height);
console.log(); console.log();
return page.getOperatorList().then(function (opList) { return page.getOperatorList().then(function (opList) {
var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs); const svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs);
svgGfx.embedFonts = true; svgGfx.embedFonts = true;
return svgGfx.getSVG(opList, viewport).then(function (svg) { return svgGfx.getSVG(opList, viewport).then(function (svg) {
return writeSvgToFile(svg, getFilePathForPage(pageNum)).then( return writeSvgToFile(svg, getFilePathForPage(pageNum)).then(
@ -126,7 +127,7 @@ loadingTask.promise
}); });
}; };
for (var i = 1; i <= numPages; i++) { for (let i = 1; i <= numPages; i++) {
lastPromise = lastPromise.then(loadPage.bind(null, i)); lastPromise = lastPromise.then(loadPage.bind(null, i));
} }
return lastPromise; return lastPromise;

View File

@ -27,21 +27,21 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Some PDFs need external cmaps. // Some PDFs need external cmaps.
// //
var CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/"; const CMAP_URL = "../../node_modules/pdfjs-dist/cmaps/";
var CMAP_PACKED = true; const CMAP_PACKED = true;
var DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf"; const DEFAULT_URL = "../../web/compressed.tracemonkey-pldi-09.pdf";
var container = document.getElementById("viewerContainer"); const container = document.getElementById("viewerContainer");
var eventBus = new pdfjsViewer.EventBus(); const eventBus = new pdfjsViewer.EventBus();
// (Optionally) enable hyperlinks within PDF files. // (Optionally) enable hyperlinks within PDF files.
var pdfLinkService = new pdfjsViewer.PDFLinkService({ const pdfLinkService = new pdfjsViewer.PDFLinkService({
eventBus, eventBus,
}); });
var pdfViewer = new pdfjsViewer.PDFViewer({ const pdfViewer = new pdfjsViewer.PDFViewer({
container, container,
eventBus, eventBus,
linkService: pdfLinkService, linkService: pdfLinkService,
@ -56,7 +56,7 @@ eventBus.on("pagesinit", function () {
}); });
// Loading document. // Loading document.
var loadingTask = pdfjsLib.getDocument({ const loadingTask = pdfjsLib.getDocument({
url: DEFAULT_URL, url: DEFAULT_URL,
cMapUrl: CMAP_URL, cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,

View File

@ -13,17 +13,17 @@
* limitations under the License. * limitations under the License.
*/ */
var PDF_PATH = "../../web/compressed.tracemonkey-pldi-09.pdf"; const PDF_PATH = "../../web/compressed.tracemonkey-pldi-09.pdf";
var PAGE_NUMBER = 1; const PAGE_NUMBER = 1;
var PAGE_SCALE = 1.5; const PAGE_SCALE = 1.5;
var SVG_NS = "http://www.w3.org/2000/svg"; const SVG_NS = "http://www.w3.org/2000/svg";
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsLib.GlobalWorkerOptions.workerSrc =
"../../node_modules/pdfjs-dist/build/pdf.worker.js"; "../../node_modules/pdfjs-dist/build/pdf.worker.js";
function buildSVG(viewport, textContent) { function buildSVG(viewport, textContent) {
// Building SVG with size of the viewport (for simplicity) // Building SVG with size of the viewport (for simplicity)
var svg = document.createElementNS(SVG_NS, "svg:svg"); const svg = document.createElementNS(SVG_NS, "svg:svg");
svg.setAttribute("width", viewport.width + "px"); svg.setAttribute("width", viewport.width + "px");
svg.setAttribute("height", viewport.height + "px"); svg.setAttribute("height", viewport.height + "px");
// items are transformed to have 1px font size // items are transformed to have 1px font size
@ -33,13 +33,13 @@ function buildSVG(viewport, textContent) {
textContent.items.forEach(function (textItem) { textContent.items.forEach(function (textItem) {
// we have to take in account viewport transform, which includes scale, // we have to take in account viewport transform, which includes scale,
// rotation and Y-axis flip, and not forgetting to flip text. // rotation and Y-axis flip, and not forgetting to flip text.
var tx = pdfjsLib.Util.transform( const tx = pdfjsLib.Util.transform(
pdfjsLib.Util.transform(viewport.transform, textItem.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]; const style = textContent.styles[textItem.fontName];
// adding text element // adding text element
var text = document.createElementNS(SVG_NS, "svg:text"); const text = document.createElementNS(SVG_NS, "svg:text");
text.setAttribute("transform", "matrix(" + tx.join(" ") + ")"); text.setAttribute("transform", "matrix(" + tx.join(" ") + ")");
text.setAttribute("font-family", style.fontFamily); text.setAttribute("font-family", style.fontFamily);
text.textContent = textItem.str; text.textContent = textItem.str;
@ -50,13 +50,13 @@ function buildSVG(viewport, textContent) {
function pageLoaded() { function pageLoaded() {
// Loading document and page text content // Loading document and page text content
var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH }); const loadingTask = pdfjsLib.getDocument({ url: PDF_PATH });
loadingTask.promise.then(function (pdfDocument) { loadingTask.promise.then(function (pdfDocument) {
pdfDocument.getPage(PAGE_NUMBER).then(function (page) { pdfDocument.getPage(PAGE_NUMBER).then(function (page) {
var viewport = page.getViewport({ scale: PAGE_SCALE }); const viewport = page.getViewport({ scale: PAGE_SCALE });
page.getTextContent().then(function (textContent) { page.getTextContent().then(function (textContent) {
// building SVG and adding that to the DOM // building SVG and adding that to the DOM
var svg = buildSVG(viewport, textContent); const svg = buildSVG(viewport, textContent);
document.getElementById("pageContainer").appendChild(svg); document.getElementById("pageContainer").appendChild(svg);
}); });
}); });

View File

@ -3,27 +3,27 @@
// Hello world example for webpack. // Hello world example for webpack.
var pdfjsLib = require("pdfjs-dist"); const pdfjsLib = require("pdfjs-dist");
var pdfPath = "../learning/helloworld.pdf"; const pdfPath = "../learning/helloworld.pdf";
// Setting worker path to worker bundle. // Setting worker path to worker bundle.
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsLib.GlobalWorkerOptions.workerSrc =
"../../build/webpack/pdf.worker.bundle.js"; "../../build/webpack/pdf.worker.bundle.js";
// Loading a document. // Loading a document.
var loadingTask = pdfjsLib.getDocument(pdfPath); const loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise loadingTask.promise
.then(function (pdfDocument) { .then(function (pdfDocument) {
// Request a first page // Request a first page
return pdfDocument.getPage(1).then(function (pdfPage) { return pdfDocument.getPage(1).then(function (pdfPage) {
// Display page on the existing canvas with 100% scale. // Display page on the existing canvas with 100% scale.
var viewport = pdfPage.getViewport({ scale: 1.0 }); const viewport = pdfPage.getViewport({ scale: 1.0 });
var canvas = document.getElementById("theCanvas"); const canvas = document.getElementById("theCanvas");
canvas.width = viewport.width; canvas.width = viewport.width;
canvas.height = viewport.height; canvas.height = viewport.height;
var ctx = canvas.getContext("2d"); const ctx = canvas.getContext("2d");
var renderTask = pdfPage.render({ const renderTask = pdfPage.render({
canvasContext: ctx, canvasContext: ctx,
viewport, viewport,
}); });

View File

@ -1,5 +1,5 @@
var webpack = require("webpack"); // eslint-disable-line no-unused-vars const webpack = require("webpack"); // eslint-disable-line no-unused-vars
var path = require("path"); const path = require("path");
module.exports = { module.exports = {
context: __dirname, context: __dirname,