HTML to PDF — Angular

Erwan LE TUTOUR
2 min readFeb 4, 2021

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Erwan LE TUTOUR
Erwan LE TUTOUR

Written by Erwan LE TUTOUR

Passionate java developer who want to share.

No responses yet

Write a response