Getting a screenshot in PDF.JS is pretty simple since the functionality is already provided. You just have to know what is needed.
Remember, copying an image to clipboard varies in some browsers and some of them do not even allow it so the only thing you can do is either save it as an image, open it in a different window or use the image data URI as the source of the IMG HTML tag.
To get the screenshot of a PDF page in PDF.JS, you only need to do the following:
- Use the getPage() function.
- Within its code block, get the viewport according to the scale value of your choosing (or use the current scale value).
- Render the page’s Canvas context.
- Crop the Canvas based on your x,y coordinate and width and height.
Here is a sample code on how to get the PDF page’s Canvas.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
PDFViewerApplication.pdfDocument.getPage(pageNumber).then(function(page) { var viewport = page.getViewport(PDFViewerApplication.pdfViewer.currentScale); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var renderContext = { canvasContext: ctx, viewport: viewport }; canvas.height = viewport.height; canvas.width = viewport.width; page.render(renderContext).then(function() { // do your cropping to only take part of the canvas as screenshot here // once cropping is done to the new canvas, use toDataURL() to open a new window with the screenshot as an image window.open(croppedCanvas.toDataURL('image/png')); }); }); |