Dittofi

HTML to PDF Generation with wkhtmltopdf on AWS Lambda (Using JavaScript)

2nd December 2024

If you’re a developer and have a need to generate PDF documents from HTML, one tool you might consider is wkhtmltopdf. This open-source library allows you to convert HTML files to PDFs with a high degree of control over the resulting document. In this blog post, we’ll look at how to use wkhtmltopdf in a JavaScript application running on AWS Lambda.

Setting up wkhtmltopdf on AWS Lambda

One of the challenges of using wkhtmltopdf on AWS Lambda is that it is not available as a native package in the AWS Lambda environment. However, we can work around this by creating a custom runtime that includes the library. 

Here’s how to do it:

Create a new folder on your local machine and navigate to it in the terminal.

Download the wkhtmltopdf static binary for your operating system from the wkhtmltopdf downloads page.

Unzip the downloaded file and copy the binary to your project folder.

Create a file named Dockerfile in your project folder with the following contents:

FROM amazonlinux:2 
COPY wkhtmltopdf /usr/local/bin/wkhtmltopdf CMD ["wkhtmltopdf"]

 

This Dockerfile creates a custom runtime image based on Amazon Linux 2, copies the wkhtmltopdf binary to the /usr/local/bin directory, and sets it as the default command.

Build the Docker image by running the following command:

docker build -t wkhtmltopdf .

 

Push the image to Amazon Elastic Container Registry (ECR). You can do this by following the instructions in the AWS documentation.

Create a new AWS Lambda function and select the custom runtime you just created in the runtime dropdown.

Using wkhtmltopdf in your lambda function

Now that you have wkhtmltopdf set up on your Lambda function, you can use it to convert HTML to PDF. Here’s an example of how to do it using the child_process module:

const childProcess = require('child_process');
exports.handler = async (event) => {
  const html = '<h1>Hello, World!</h1>';
  const pdf = childProcess.spawnSync('wkhtmltopdf', ['-', '-'], {
    input: html,
    encoding: 'binary'
  });

  const response = {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/pdf'
    },
    isBase64Encoded: true,
    body: pdf.stdout.toString('base64')
  };

  return response;
};

In this example, we use the spawnSync function from the child_process module to run the wkhtmltopdf binary with the – and – arguments.

You can find the open source project of our pdf generator here: https://github.com/dittofi/dittofi-html-to-pdf.

Related posts...
Share your idea with us
Drive your business with our Hybrid NoCode Platform
James Virgo Headshot
Article by
James Virgo
Co-Founder of Dittofi
Build your app today
Create an enterprise grade app today
*No credit card required

Solverwp- WordPress Theme and Plugin

⸺ Receive the latest news

Subscribe To Our Weekly Newsletter

Get notified about new articles and events