Cannot open pdf aws lambda

96 views Asked by At

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:

enter image description here

1

There are 1 answers

0
Bhavesh Parvatkar On

Few things are you are doing it incorrect:

  1. The function params has (event, context, callback) and not (req, res).

  2. API response should have base64 data. For that you can use saveAsBase64.

  3. In case you have API Gateway connected to it. Then you will have to enable Binary media types.

  4. Also note that drawText method takes normal string and not HTML string. Although it will work but it will render entire HTML string.

Demo example:

const { PDFDocument } = require("pdf-lib");

export async function hello(event, context) {
  try {
    const pdfDoc = await PDFDocument.create();
    const text = "Hello World!";
    const page = pdfDoc.addPage([350, 400]);
    page.moveTo(110, 200);
    page.drawText(text);
    const pdfBase64 = await pdfDoc.saveAsBase64();
    const filename = "example.pdf";

    return {
      statusCode: 200,
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `inline; filename=${filename}`,
      },
      body: pdfBase64,
      isBase64Encoded: true,
    };
  } catch (error) {
    console.error("Error generating PDF:", error);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: "Internal Server Error" }),
    };
  }
}

Enable Binary media types

  1. Goto your API dashboard
  2. From the left panel, goto API Settings
  3. Under Binary media types, Select Manage Media Types
  4. Add "*/*" to enable all binary support. You can restrict it based on your requirements.
  5. Goto Resources from the left panel and Deploy API from the top right side.

NOTE: 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.