Serverless — PDF Generation

Introduction

Pre-requisites

Installation

npm install --global serverless
git clone git@github.com:JMSantos94/pug-a-tron.git

What’s Included

service: demo-pdf-generationprovider:
name: aws
runtime: nodejs10.x
stage: ${opt:stage, 'dev'}
functions:
pug-a-tron:
role: customRole
handler: src/index.handler
events:
- http:
path: pdf-generator
method: get
cors: true
plugins:
- serverless-offline
- serverless-webpack
package:
individually: true
custom:
webpack:
webpackConfig: './webpack.config.js'
includeModules: true,
packager: 'yarn'
const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
stats: 'minimal',
entry: slsw.lib.entries,
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
resolve: {
extensions: ['.js', '.jsx', '.json'],
},
target: 'node',
optimization: { /* ... */ },
performance: { /* ... */ },
devtool: 'nosources-source-map',
externals: [nodeExternals()],
plugins: [ /* ... */ ],
module: {
rules: [
{
test: /\\.jsx?$/,
exclude: /node_modules/,
use: 'babel-loader',
},
/* ... */
],
},
output: {
libraryTarget: 'commonjs2',
path: path.join(__dirname, '.webpack'),
filename: '[name].js',
sourceMapFilename: '[file].map',
},
};
{
"comments": false,
"presets": [
[
"@babel/env",
{
"targets": {
"node": "10.15"
}
}
],
"@babel/preset-react"
],
"plugins": ["source-map-support"]
}
import React from 'react';
import ReactPDF, { Text, Font, StyleSheet, Document, Page } from '@react-pdf/renderer';
const handler = async (event, ctx) => {
const pdfStream= await ReactPDF.renderToStream(
<Document>
<Page style={styles.body}>
<Text style={styles.title}>
Hello World
</Text>
</Page>
</Document>,
);
return { /* ... */ };
};
Font.register({
family: 'Oswald',
/* ... */
});
// PDF Styles
const styles = StyleSheet.create({ /* ... */ });
export { handler };
FROM amazonlinux2:latestRUN curl --silent --location <https://rpm.nodesource.com/setup_10.x> | bash -
RUN yum install -y nodejs zip awscli
RUN npm install -g yarn serverless
RUN mkdir /app
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn --pure-lockfile
COPY . ./CMD sls deploy --stage prod
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<dir>./fonts</dir>
<cachedir>/tmp/fonts-cache/</cachedir>
<config></config>
</fontconfig>
process.env.FONTCONFIG_PATH = __dirname;
const { registerFont } = require('canvas');registerFont(
'./fonts/your-custom-font.tff',
{ family: 'customfont' }
)

Deploying

yarn run docker:build
yarn run docker:run

Conclusion

Senior Frontend Developer @ GumGum, Inc.