A common requirement is to generate images from HTML or CSS code e.g. for barcodes or embedding contents into emails. Running this job on a dedicated server environment often results in over-provisioning the ressources that’s why AWS Lambda is the perfect solution for that task.
is a serverless computing service which means you do not need to take care of provisioning your hardware, updating the software and upgrading CPU ressources because Amazon does all that for you – without you even noticing that. Therefore it is an awesome use-case for “on-off” workloads. In this blog post we will walk through the different steps that are necessary to run the tool on AWS Lambda to generate images from HTML.
By the way, this mechanism is also used in our email recommendations feature, which I suggest to take a look at if you have not done so already.
Up until the mid of 2019 AWS Lambda supported Node.JS version 8.x and the Lambda computing engine used the Amazon Linux AMI version 1. At that time you could easily use an existing and run the wkhtmltoimage tool and e.g. save the resulting image to an AWS S3 bucket. With the end of the support period of Node.JS 8.x and the switch to Node.JS version 10.x Amazon also decided to , which unfortunately does not have the required prerequisites installed any more in order to successfully run the wkhtmltoimage binary.
To install the required software components you must include the already compiled library files into your Node.JS function ZIP package that is deployed to AWS Lambda. To compile the libraries the easiest way is to launch a new EC2 instance with the appropriate image.
- Launch a new micro EC2 instance with the Amazon Linux 2 AMI
- Execute the command to install the necessary software packages
sudo yum install -y yum-utils rpmdevtools libXrender fontconfig urw-fonts libXext freetype libX11 expat libxcb libXau libjpeg-turbo libpng
- Execute the commands to download the libraries and extract the compiled files
yumdownloader libXrender.x86_64 fontconfig.x86_64 libXext.x86_64 freetype.x86_64 libX11.x86_64 expat.x86_64 libxcb.x86_64 libXau.x86_64 libjpeg-turbo.x86_64 libpng.x86_64
The Lambda environment uses a 64-bit architecture, therefore it is important to extract the libraries in the x86_64 format.
- Execute the commands
sudo mkdir -p /var/task
sudo chown ec2-user:ec2-user /var/task
cp /tmp/*/usr/lib64/* /var/task
- Download the compiled libraries in the folder /var/task from the EC2 instance e.g. with scp command utility
- The final step is to include the following files into your Node.JS zip package together with the wkhtmltoimage binary:
libX11.so.6, libXau.so.6, libXext.so.6, libXrender.so.1, libexpat.so.1, libfontconfig.so.1, libfreetype.so.6, libjpeg.so.62, libpng15.so.15, libxcb.so.1
Now you only need to implement your index.js file to generate images from HTML. You can find an example on the .