-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
100 lines (82 loc) · 2.56 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const pdf = 'document.pdf';
// Import the necessary module from pdf.js
import { GlobalWorkerOptions, getDocument } from 'https://cdn.jsdelivr.net/npm/pdfjs-dist@4.5.136/build/pdf.min.mjs';
// Set worker source
GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@4.5.136/build/pdf.worker.min.mjs';
const initialState = {
pdfDoc: null,
currentPage: 1,
pageCount: 0,
zoom: 1,
};
// Render the page
const renderPage = () => {
initialState.pdfDoc.getPage(initialState.currentPage).then((page) => {
const canvas = $("#canvas")[0];
const ctx = canvas.getContext("2d");
const viewport = page.getViewport({ scale: initialState.zoom });
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
const renderCtx = {
canvasContext: ctx,
viewport: viewport,
};
page.render(renderCtx);
// Update current page number
$("#page_num").text(initialState.currentPage);
});
};
// Load the Document
getDocument(pdf).promise.then((data) => {
initialState.pdfDoc = data;
$("#page_count").text(initialState.pdfDoc.numPages);
renderPage();
}).catch((err) => {
alert(err.message);
});
// Show Previous Page
const showPrevPage = () => {
if (initialState.pdfDoc === null || initialState.currentPage <= 1) return;
initialState.currentPage--;
$("#current_page").val(initialState.currentPage);
renderPage();
};
// Show Next Page
const showNextPage = () => {
if (initialState.pdfDoc === null || initialState.currentPage >= initialState.pdfDoc.numPages) return;
initialState.currentPage++;
$("#current_page").val(initialState.currentPage);
renderPage();
};
// Zoom In
const zoomIn = () => {
if (initialState.pdfDoc === null) return;
initialState.zoom *= 1.25;
renderPage();
};
// Zoom Out
const zoomOut = () => {
if (initialState.pdfDoc === null) return;
initialState.zoom *= 0.8;
renderPage();
};
// Bind events using jQuery
$("#prev_page").on("click", showPrevPage);
$("#next_page").on("click", showNextPage);
$("#zoom_in").on("click", zoomIn);
$("#zoom_out").on("click", zoomOut);
// Keypress Event for jumping to a page
$("#current_page").on("keypress", (event) => {
if (initialState.pdfDoc === null) return;
if (event.keyCode === 13) {
let desiredPage = parseInt($("#current_page").val());
initialState.currentPage = Math.min(Math.max(desiredPage, 1), initialState.pdfDoc.numPages);
$("#current_page").val(initialState.currentPage);
renderPage();
}
});
// Optional Print Support
$(".print-button").on("click", () => {
window.print();
});