Node.js – Convert PDF base64 to PNG base64 on Lambda

I recently developed an application running on Lambda Node.js 14.x, lost lots of time on this part. So I think this post may help someone to save their time. Don’t hesitate to leave a comment below if you found this post is hard to understand or if you have any questions.

1. NPM package

I use pdf2pic for converting PDF to PNG.

npm i pdf2pic

2. serverless.yaml

pdf2pic requires some native dependencies so we need to add required layers to Lambda function:

functions:
  app:
    handler: yours.handler
    layers:
      - arn:aws:lambda:us-west-2:175033217214:layer:graphicsmagick:2
      - arn:aws:lambda:us-west-2:764866452798:layer:ghostscript:9

Replace us-west-2 with your Lambda function region.

3. JS Code

let convertPdfToPng = require('pdf2pic').fromBase64;
let fs = require('fs').promises;

async function pdf2png(pdfData, tmpFilename) {
    const pdf2picOptions = {
        format: 'png',
        width: 768, // x2 4inch
        height: 1152, // x2 6inch
        density: 300,
        savePath: '/tmp',
        saveFilename: tmpFilename
    };
    const pageNumber = 1; // First page

    return new Promise(function(resolve, reject) {
        const convert = convertPdfToPng(pdfData, pdf2picOptions);
        convert(pageNumber).then((response) => {
            fs.readFile(response.path, {encoding: 'base64'}).then(function (data) {
                resolve(data);

                // remove the temp file to save space
                fs.unlink(response.path, function (err) {
                    if (err) throw err;
                });
            });
        });
    });
}

Usage:

let pngBase64 = await pdf2png(pdfBase64, aUniqueValueVariable)

Notes:

  1. Don’t just copy the code
  2. Modify pdf2picOptions to suit your purpose
  3. Modify pageNumber to suit your purpose (you may want to pass it as a ref variable)
  4. Each time you call the function, you need to pass a unique value to tmpFilename variable to prevent read/write conflict between multiple processes.

Refs:

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ego Bay
Ego Bay
2 years ago

I’m getting timeout in AWS lambda. Could you share how you integrate with handler function?

2
0
Would love your thoughts, please comment.x
()
x