Created
October 31, 2019 16:29
-
-
Save kharandziuk/9a6b380b691710256901b89b0af02952 to your computer and use it in GitHub Desktop.
Node Pdf to png without system level dependencies
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
| var Canvas = require('canvas'); | |
| var assert = require('assert'); | |
| var fs = require('fs'); | |
| var pdfjsLib = require('pdfjs-dist'); | |
| function NodeCanvasFactory() {} | |
| NodeCanvasFactory.prototype = { | |
| create: function NodeCanvasFactory_create(width, height) { | |
| assert(width > 0 && height > 0, 'Invalid canvas size'); | |
| var canvas = Canvas.createCanvas(width, height); | |
| var context = canvas.getContext('2d'); | |
| return { | |
| canvas: canvas, | |
| context: context, | |
| }; | |
| }, | |
| reset: function NodeCanvasFactory_reset(canvasAndContext, width, height) { | |
| assert(canvasAndContext.canvas, 'Canvas is not specified'); | |
| assert(width > 0 && height > 0, 'Invalid canvas size'); | |
| canvasAndContext.canvas.width = width; | |
| canvasAndContext.canvas.height = height; | |
| }, | |
| destroy: function NodeCanvasFactory_destroy(canvasAndContext) { | |
| assert(canvasAndContext.canvas, 'Canvas is not specified'); | |
| // Zeroing the width and height cause Firefox to release graphics | |
| // resources immediately, which can greatly reduce memory consumption. | |
| canvasAndContext.canvas.width = 0; | |
| canvasAndContext.canvas.height = 0; | |
| canvasAndContext.canvas = null; | |
| canvasAndContext.context = null; | |
| }, | |
| }; | |
| // Relative path of the PDF file. | |
| const toImg = async (pdfData) => { | |
| const pdfDocument = await pdfjsLib.getDocument(new Uint8Array(pdfData)).promise | |
| // Get the first page. | |
| const page = await pdfDocument.getPage(0) | |
| // Render the page on a Node canvas with 100% scale. | |
| const viewport = page.getViewport({ scale: 1.0, }); | |
| const canvasFactory = new NodeCanvasFactory(); | |
| const canvasAndContext = canvasFactory.create(viewport.width, viewport.height); | |
| const renderContext = { canvasContext: canvasAndContext.context, | |
| viewport: viewport, | |
| canvasFactory: canvasFactory, | |
| }; | |
| await page.render(renderContext).promise | |
| return canvasAndContext.canvas.toBuffer(); | |
| } | |
| const pdfURL = 'test.pdf'; | |
| toImg(fs.readFileSync(pdfURL)).then(buf => process.stdout.write(buf)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment