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.
Contents
hide
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:
- Don’t just copy the code
- Modify
pdf2picOptionsto suit your purpose - Modify
pageNumberto suit your purpose (you may want to pass it as a ref variable) - Each time you call the function, you need to pass a unique value to
tmpFilenamevariable to prevent read/write conflict between multiple processes.
Refs:
- https://www.npmjs.com/package/pdf2pic
- https://github.com/rpidanny/gm-lambda-layer
- https://github.com/shelfio/ghostscript-lambda-layer
I’m getting timeout in AWS lambda. Could you share how you integrate with handler function?
I just call the function in lambda handler, nothing special. In your case, I think you can try to increase memorySize to 256 and timeout to 5 or 10.