HTML to PDF — Angular

Use Case
With the covid-19 pandemic and the lockdown period, I reopened my cookbooks to take up my free time.
Being someone who likes to share his experiences, I created a web application where I shared the recipes I had tried, as well as tips for making them.
But a computer is not something practical in the kitchen, so I looked for a solution to export the recipes to a more convenient format to use: a printable PDF.
jsPDF & html2canvas
Dependencies
Firstly run the following command to add the dependencies to your package management
npm i html2canvas
npm i jspdf
With that done, you’re all good to create your PDF.
Creating the PDF
Now that you have installed the dependencies, we can begin to work, to do that we need to import the installed dependencies
then simply declare the document indicating:
- orientation (p / portrait / l / landscape)
- the unit
- the format (either a string like A4, or an array of dimensions [21,29.7])
In this example, we generate a A4 portrait mode PDF, the units of which are expressed in centimetres.
Fill the File
Now that we have declared our file, we now need to add content to it, an empty file is not very useful.
To do this we will use html2Canvas which will make a screenshot of an HTML element defined for example by its id and then add it in the PDF.
Pros and cons
Pro
- little line of code to write.
- easy to use.
Cons
- The PDF actually contains only one image.
- As the image will be stretched/contracted to fill the page, its quality can be strongly impacted.