showing results for - "pdf js tutorial for beginners"
Albie
20 Apr 2020
1/*
2    This code comes from Vincent Lab
3    And it has a video version linked here: https://www.youtube.com/watch?v=JZHyvG93G2I
4*/
5
6const url = "/dummy.pdf";
7
8(async function () {
9
10    // Specified the workerSrc property
11    pdfjsLib.GlobalWorkerOptions.workerSrc = "//mozilla.github.io/pdf.js/build/pdf.worker.js";
12
13    // Create the PDF document
14    const doc = await pdfjsLib.getDocument(url).promise;
15
16    const minPage = 1;
17    const maxPage = doc._pdfInfo.numPages;
18    let currentPage = 1;
19
20    // Get page 1
21    await getPage(doc, currentPage);
22
23    // Display the page number
24    document.getElementById("pageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`;
25
26    // The previous button click event
27    document.getElementById("previous").addEventListener("click", async () => {
28
29        if (currentPage > minPage) {
30
31            // Get the previous page
32            await getPage(doc, currentPage--);
33
34            // Display the page number
35            document.getElementById("pageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`;
36
37        }
38
39    });
40
41    // The next button click event
42    document.getElementById("next").addEventListener("click", async () => {
43
44        if (currentPage < maxPage) {
45
46            // Get the next page
47            await getPage(doc, currentPage++);
48
49            // Display the page number
50            document.getElementById("pageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`;
51
52        }
53
54    });
55
56})();
57
58
59async function getPage(doc, pageNumber) {
60
61    if (pageNumber >= 1 && pageNumber <= doc._pdfInfo.numPages) {
62
63        // Fetch the page
64        const page = await doc.getPage(pageNumber);
65
66        // Set the viewport
67        const viewport = page.getViewport({ scale: 1.5 });
68
69        // Set the canvas dimensions to the PDF page dimensions
70        const canvas = document.getElementById("canvas");
71        const context = canvas.getContext("2d");
72        canvas.height = viewport.height;
73        canvas.width = viewport.width;
74
75        // Render the PDF page into the canvas context
76        return await page.render({
77            canvasContext: context,
78            viewport: viewport
79        }).promise;
80
81    } else {
82        console.log("Please specify a valid page number");
83    }
84}