Created
February 10, 2024 16:44
-
-
Save urkle/5167fdc74bd74e27a0db35f69d5ba65a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<canvas id="the-canvas" style="border:1px solid black"></canvas> | |
<input id='pdf' type='file'/> | |
<script type="importmap"> | |
{ | |
"imports": { | |
"pdf": "https://mozilla.github.io/pdf.js/build/pdf.mjs", | |
"pdfWorker": "https://mozilla.github.io/pdf.js/build/pdf.worker.mjs" | |
} | |
} | |
</script> | |
<script type="module"> | |
import * as pdfJS from 'pdf'; | |
import * as pdfWorker from 'pdfWorker'; | |
// | |
// preload the pdf worker to avoid yet another cross-origin issue (workers need the URL of | |
// the script to be loaded, and dynamically loading a cross-origin script does | |
// not work) | |
// | |
//pdfJS.GlobalWorkerOptions.workerSrc = pdfWorker; | |
globalThis.pdfjsWorker = pdfWorker; | |
window.pdfJS = pdfJS; | |
async function loadPdf(doc) { | |
const pdf = await pdfJS.getDocument(doc).promise; | |
// | |
// Fetch the first page | |
// | |
const page = await pdf.getPage(1); | |
const scale = 1.5; | |
const viewport = page.getViewport({ scale }); | |
// | |
// Prepare canvas using PDF page dimensions | |
// | |
const canvas = document.getElementById('the-canvas'); | |
const context = canvas.getContext('2d'); | |
canvas.height = viewport.height; | |
canvas.width = viewport.width; | |
// | |
// Render PDF page into canvas context | |
// | |
await page.render({canvasContext: context, viewport: viewport}).promise; | |
console.log(canvas.toDataURL('image/jpeg')); | |
} | |
// | |
// Asynchronous download PDF as an ArrayBuffer | |
// | |
const pdf = document.getElementById('pdf'); | |
pdf.onchange = function(ev) { | |
let file; | |
if (file = document.getElementById('pdf').files[0]) { | |
const fileReader = new FileReader(); | |
fileReader.onload = (ev) => { | |
loadPdf(fileReader.result); | |
}; | |
fileReader.readAsArrayBuffer(file); | |
} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment