Skip to content

Instantly share code, notes, and snippets.

@tertek
Created April 20, 2021 09:01
Show Gist options
  • Save tertek/d464dd1ea59e4987fe76f499ed5076e2 to your computer and use it in GitHub Desktop.
Save tertek/d464dd1ea59e4987fe76f499ed5076e2 to your computer and use it in GitHub Desktop.
PDF to Thumbnail Image with pdf.js
function makeThumb(page) {
// draw page to fit into 96x96 canvas
var vp = page.getViewport({ scale: 1, });
var canvas = document.createElement("canvas");
var scalesize = 1;
canvas.width = vp.width * scalesize;
canvas.height = vp.height * scalesize;
var scale = Math.min(canvas.width / vp.width, canvas.height / vp.height);
console.log(vp.width, vp.height, scale);
return page.render({ canvasContext: canvas.getContext("2d"), viewport: page.getViewport({ scale: scale }) }).promise.then(function () {
return canvas;
});
}
function renderPDF() {
var temp = "https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf";
pdfjsLib.getDocument(temp).promise.then(function (doc) {
var pages = []; while (pages.length < 1) pages.push(pages.length + 1);
return Promise.all(pages.map(function (num) {
// create a div for each page and build a small canvas for it
var div = document.getElementById("thumbnail-wrapper");
return doc.getPage(num).then(makeThumb)
.then(function (canvas) {
var img = new Image();
img.src = canvas.toDataURL();
div.appendChild(img);
");
});
}));
}).catch(console.error);
}
renderPDF();
<!DOCTYPE html>
<html>
<head>
<title>PDF to Thumbnail Image</title>
</head>
<body>
<div id="thumbnail-wrapper"></div>
<script type="text/javascript" src="/build/pdf.js"></script>
<script type="text/javascript" src="/pdfToThumbnailImage.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment