Make PDFs Automatically with an AWS API - NodeJS Typescript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
do you want to learn how you can create an api which can dynamically create a certificate and output a pdf for your users in this video that is exactly what i'm going to show you how to do [Music] hi guys my name is sam with complete coding but our aim is to make you into the best aws and serverless developer that you can be in this video we're going to be using typescript to create an api that allows us to send up the name of a user and it will automatically generate a certificate for that user we're going to be creating an api gateway endpoint using aws lambda and storing the certificate templates in s3 once we've deployed this we're going to have an api which will automatically generate a certificate just like this one and you can customize the name dynamically in your api so let's jump into the code and see how we can create our api so now that we're in the code i'm in a repo where i've just created it and i create it using the serverless create dash dash template and for this we're using aws dash nodejs dash type script and that is the template we're using here if we look inside our folder structure we can see that there is the default handler.ts which comes when you run this create script all i've done is installed the npm packages required so now the first thing we need to do is well the way i like to do it is to restructure this a little bit so i'm going to create a new folder called source inside that i'm going to create functions and inside that a folder for the function i'm going to create in this case it's going to be create certificate and i'm just going to copy that for later and now we can move our handler into that folder and i also like to rename this to index.ts and update the name of the function to handler so now that we've got that all set up we can go into our serverless.ts and just correct the api and function definitions in this section so now the function is going to be called create certificate and the handler i'm going to start from scratch it's going to be source slash function slash create certificate index dot handler the method in our case we're not going to do a get request we're actually going to do a post request and the path i'm going to do as certificate so every time we do a post to forward slash certificate on our api it's going to trigger this function so if we jump into our create we are going to do a couple of things the first thing is we are going to use a package which is called pdf lib so to use that first we need to install it so npm install minus s and it is pdf dash lib and whilst that is installing we can actually import that so import curly brackets pdf document from and then it's pdf lib so now that we've imported that what this document tool does is it allows us to read a pdf that may be a template and then populate fields inside that pdf so for us the first thing we need to do is get the body of the api request so const body and this is normally jason dot pass event dot body so this is probably what you do most of the time when you need to get the event body but later on we're going to be actually changing this api to be working with a base 64 encoded uh string so that we can actually send the pdf as a base 64 encoded string what we what this means is if we go into our serverless.ts and we find our api gateway config we're going to be making one small change in here which is to set binary media types and that's going to be an array with a string of star forward slash star what this means is that both the input and the output of our apis is going to be turned into a binary string this does mean we need to make a bit of a difference in our api request so back in our handler instead of doing just jsonpassevent.buddy we need to do json.pass of buffer dot from event.body and we have to specify that the event.body equals base64 and then turn this base64 buffer into a string so we're taking the event body which is base64 turning it into a buffer and then turning that into a string which we can then use jsonparson to get the body this is a little bit of an extra step but is required if you want to send the actual pdf as a response so now that we have the body we're actually going to get a template from s3 so const template equals await s3 dot get object and here it's saying there's an error because we can't find s3 which is exactly kind of what we expect so here we want to import and it's capital s 3 from aws sdk and this becomes part of every lambda and then on the line after that we can say const lowercase s3 equals a new version of the s3 uppercase like that so here now we have s3 and we're calling get object and this takes a parameter of the bucket we're going to pass the bucket name in as an environment variable so we can do process dot end dot bucket name and then the second part is what file name do we want to get and they call that the key and in our case the key is going to be body dot certificate template so now that we've defined the get object we want to turn this into a promise by adding dot promise at the end so that this will be awaited and the template will actually be the response that we want now we need to load this pdf template into this pdf document tool so we do that by saying const pdf doc equals await pdf document dot load and now we want to load in template dot body because that is the going to be the content of the pdf and we actually want to turn this into a string and we want to say that it's going to be a base 64 string so now we have our pdf document we can start doing some interesting things first we can get the form so const form equals pdf doc dot get form and the form is the part of the pdf document that is actually editable so for us that is going to be the name of the person who is receiving the certificate but you could add a lot more next we want to actually rename one of the fields so form dot get text field and we've named the field as name and before we actually set the text for that we want to set alignment and that is going to be text alignment dot center where the value of text alignment is also imported from the pdf lib this just makes sure that the name is in the center of the page and that looks a lot nicer next what we can do is cop get that same name form field and this time we're going to do a set text and this is going to be body dot name so whatever name is passed up in the body of the api request is the one that is going to be added to this field finally now that we've added our customization to our pdf we want to do form dot flatten and that just locks all of these in place so they can't be edited later if you wanted you could add a lot more fields into your form and add pass up a lot more data inside your api such as the date it was awarded if it has an expiry date or you could even dynamically change the name of the certificate if you wanted so now that we've completed that form what we want to do is we want to actually get that ready to turn into an api response so we're going to do that by saying const pdf out equals again we're going to await and it's going to be the pdf doc which is the document we loaded it into and then we'll do dot save as base 64 which is going to turn this into a base base64 string now that we have that we can create our response so i'm just going to delete this we are still going to have a status code of 200. the body is now going to be pdf out we need to set a flag of isb base 64 encoded and set that to true and then we can also set some headers such as the content dash type and set that to application forward slash pdf and also set an access control access dash control dash allow dash origin and set that to star which means that any you any web page is allowed to make a request to this api so this is all good and we have all of our logic but sometimes things might go wrong maybe the s3 object isn't in the place it needs to be or they don't pass up a name or even they don't pass up the certificate template so in that case what we're going to do is wrap all of this in a try catch so add try at the very start and then after our return statement add a catch where we're going to catch the error so here we're going to add a console.log because it's always nice to know what the error is we also just before the catch need to add a curly brace to close off the part first part of the try and after we've console logged it we need to return an error via http so return this object with a status code of i'm going to go with a 500 although this could be a user caused error in which case it would be a 400 and i'm going to add a body and this is going to be adjacent.stringify and there's going to be a message of error dot message so that's just going to tell the user if they've made some incorrect uh request it's going to pass back the message of the error so now that we have all of this done we notice that we've used s3 so we actually need to first create an s3 bucket and then give this lambda permissions to access that s3 bucket so back in our serverless.ts to create our s3 if we go right the way to the bottom of our code so after functions we can add a resources section so the first word is resources with a lowercase r the second one is resources with an uppercase r i'm not sure why exactly they require this in serverless but it's something that we do need to do now in here we want to have the basically the bucket that stores the templates so template bucket and that is going to have a type the type is going to be aws colon colon s3 colon colon bucket we're then going to have basically just a single property and that is going to be an object and here we're going to define the bucket name and instead of just hard coding it here we're actually going to use a variable system in serverless so if we put dollar and then inside the curly braces put self colon custom dot bucket name and we copy the bucket name we can then scroll up to our custom section add the bucket name here and again we're going to mix up some hard-coded bucket name but with a little bit of customization so here we're going to call this something along the lines of my certificate templates but after that i'm going to add another reference here so again it's self colon and instead of reference in the custom section we're going to reference the provider so self colon provider dot stage so if we deploy this to dev it will add dev on the end if it's a uat or a qa it will add a uat or qa and finally if it's production it will add dash production to the end of the bucket name that's really useful because every bucket needs to be completely unique and by adding variables like this it means your different deployments won't conflict with one another so now that we have our bucket the last thing we really need to do in here is add the permissions to allow the functions to access that bucket we do that by adding i am role statements and this is going to be an array of objects and in our case we're just going to say there's an effect and the effect is allow we have an action and that action is going to be s3 with a lowercase s colon star which means that we are allowed to do anything we want in s3 and the resources sorry resource if i can spell that right and the resource we're just going to say star for now which would mean this lambda can access any of the s3 buckets in this account but for now that is okay for us as well as the access i am role statement in our code we used the bucket name dynamically so in our environment variables we need to copy the bucket name which we pass in as an environment variable to here and then that is also going to reference this bucket name so what we can do is do another string with dollar sign curly braces self colon custom dot bucket name which is going to point at the same variable we've defined in our custom section so everything will work together now that we have all of this set up we can go into our terminal and run sls deploy but i'm going to add two little extra things to my provider to make this a little bit easier to use so for me i'm running out of germany so i want to set the region to eu dash west dash one i also want to set a profile and then this is going to basically define which aws credentials from my credentials file i'm deploying with so i'm just going to copy those and paste them in for my use case you should paste in whichever credentials you have for the account that you want to deploy to now that we have all of that i'm going to run sls deploy and this is going to then create our api as well as the s3 bucket that we're going to upload our templates too this takes a little bit of time so i'll get back to you when that is done so now that has finished deploying we can see there is a single end point a post request to forward slash certificate but before we actually try and hit this we need to add our certificate to our s3 bucket so i'm just going to do this through the console for now but if you wanted to automate this you could use something like serverless s3 sync to sync all of your templates up via api so in s3 we can look at our new buckets and if i sort by creation date we can see we have the bucket of my certificate templates dash dev which is what we expect and in here i'm then just going to manually upload a file and that is on my desktop so to create this pdf i just found a template online and then used an online tool called which allows you to add a form to a pdf there's i'm going to link that in the description below so if you want to make your own templates you can just start with a blank pdf or a pdf with the styling that you like and then just add on your own form fields for things such as your name or the certificate that's being awarded i'm going to upload my serverless wizard one and i'm actually going to copy the name of that as we'll use that in our api request so if we go into first into our code and copy the url that we've been given and paste that into postman and change this to a post request because we're using postman because it's a lot easier to do a post request but this could be used for something such as when someone completes an online course they get sent a certificate and you could do this inside a lambda as an api request so we're going to set the body on this to be a raw json input and here there's going to be two things the first thing if we go back to our code we're going to be looking for body dot certificate template so certificate template and this is going to be the name of the template file that we just uploaded which in our case is serverlesswizard.pdf and the second thing is going to be a name and for this one i'm just going to go with sam williams and now what we can do is we can send that request and if i make this a bit bigger we can see that we got response of the pdf template with sam williams as the response this just means that we can make as many requests as we want and customize this field here so if i change that to bob jones make the rec make the request we now have the response of bob jones inside this certificate this can be used for loads of different things and one of the use cases i've had previously is actually creating like an itinerary or creating an order form where you need to have five or six different items in that form and we used this exact tool to add those items to a pdf template and we then sent that dynamically to the user if you wanted you could create a lot more templates and you could have a whole system where you're able to add data to templates dynamically in this video we have set up a new repo where we are able to automatically generate a pdf and dynamically fill that certificate with data such as the user's name this is a really cool concept and you can use this for loads of different things you could add more details to your certificate or you could use this for generating a delivery form or a inventory list there are loads of ideas that you could come up with and multiple different ways that this application could be used in your business if you've learned something new in this video then make sure to hit that thumbs up button as it really helps out the channel and if you haven't done already make sure to subscribe as we release regular content on aws and serverless to help you become the best developer that you can be thank you and i'll see you in the next video
Info
Channel: Complete Coding
Views: 425
Rating: undefined out of 5
Keywords: AWS, serverless, Serverless Framework, NodeJS
Id: bcikiejzfAE
Channel Id: undefined
Length: 26min 22sec (1582 seconds)
Published: Wed Nov 24 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.