I'm facing an issue with my lambda function. When I run it in Postman, the PDF isn't displayed. I've also tried the 'Send and Download' option, but it says the file doesn't have a valid format. Any suggestions?
I have an issue with this lambda function:
const { PDFDocument } = require('pdf-lib');
exports.getAll = async (req, res) => {
try {
const htmlContent = '<html><body><h1>Hello World</h1></body></html>';
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
await page.drawText(htmlContent, { x: 50, y: height - 100 });
const pdfBytes = await pdfDoc.save();
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'inline; filename=hello_world.pdf');
res.status(200).send(pdfBytes);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
When running it in Postman, the PDF is not displayed. I also tried the 'Send and Download' option, but it shows that the file does not have a valid format. Any suggestions?
My package.json :
{
"name": "formularios-pdf",
"version": "1.0.0",
"description": "description",
"main": "index.js",
"author": "author",
"license": "ISC",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"aws-serverless-express": "^3.4.0",
"axios": "^0.24.0",
"chrome-aws-lambda": "^10.1.0",
"express": "^4.17.1",
"moment": "^2.29.4",
"mysql2": "^2.3.3",
"pdf-lib": "^1.17.1"
}
}
Post man:

Few things are you are doing it incorrect:
The function params has
(event, context, callback)and not(req, res).API response should have base64 data. For that you can use
saveAsBase64.In case you have API Gateway connected to it. Then you will have to enable Binary media types.
Also note that
drawTextmethod takes normal string and not HTML string. Although it will work but it will render entire HTML string.Demo example:
Enable Binary media types
Manage Media TypesNOTE: It might take some time to reflect the changes of step 5. Took 5 minutes for me.
In case you are using Function URL, then just function deployment in enough.