How to generate PDF from HTML on AWS Lambda

aws
lambda

#1

Anyone had luck in creating a function for html to pdf generation on AWS?
The closest I could get was using wkhtmltopdf and I can get the base64 of the pdf of the html string, but when I output it to the response, I can’t open the PDF.
Any good examples?

This is the code I’m using:

import wkhtmltopdf from "wkhtmltopdf";
import MemoryStream from "memorystream";

process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];

export async function main(event, context, callback) {
    const html = '<h1>Test</h1><p>Hello world</p>';
    const memStream = new MemoryStream();

    wkhtmltopdf(html, { pageSize: 'letter' }, function(code, signal) {
        let pdf = memStream.read();
        const response = {
            statusCode: 200,
            headers: {
                'Content-type' : 'application/pdf',
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Credentials": true
            },
            body: pdf.toString('base64'),
            isBase64Encoded : true
        };
        callback(null, response);
    }).pipe(memStream);
}

And I’m also including the wkhtmltopdf binary on the root that I get from this tutorial:
https://www.drivenbycode.com/creating-pdfs-from-html-with-aws-lambda-and-api-gateway/

Thanks!


#2

I’m not sure if this is related but if you declare your handler function async then you don’t use callback. If you’re using the Node 8.10 runtime it won’t work.


#3

Take a look at this https://stackoverflow.com/questions/45348580/aws-lambda-returning-pdf-file


#4

You might also give chromeless or serverless chrome a shot:


#5

Thanks for the suggestions and guidance.

My problem was that I was testing directly on the service endpoint.
As soon as I called the service from the frontend (Javascript) and open it on a new window it worked:

window.open("data:application/pdf;base64, " + pdf);