Sometimes it’s useful to get an image for a specific object (e.g. table, a text field) from your web page by simply clicking a button. At other times, you may want to just take a screenshot of an object and place it into a specific section on your web page as an image. I’ve found two JavaScript libraries to get these jobs done: html2canvas
and jsPDF. Both libraries are available free of charge. The first library includes the logic for building a screenshot based on the DOM. The second library saves the canvas as a PDF-File.


To illustrate the syntax of the libraries, I’m going to give you a quick example of a use case from a little private project of mine.

Card games like Texas Hold’em Poker are strategic games. This means, that it is a good idea to have a winning strategy when you play it. A strategy, in turn, is a game plan for your play in specific situations against different opponents. For example, what kind of starting hands you want to raise (2Bet) in the first position (UTG = Under The Gun) and which hands you want to 4Bet (re-re-raise) if someone is re-raising (3Bet) you after you opened a hand. To illustrate the strategy it’d be nice to have a chart which gives the user a quick overview.

So we end up with a table showing starting hands for Texas Hold’em Poker. Furthermore, the user can manipulate the table to mark hands they are willing to play with their specific holding. In this example, the user wants to illustrate the situation described above. I’ve implemented this as an application running in a browser. Basically, it looks like this:

initial state


defined strategy by a user


My project displays this table on the screen. But wouldn’t it be nice to save the resulting table with a click on a button as a picture? For example, in order to learn your strategy or to share it with your friends?


To save the resulting HTML table as a PDF-File you just need to insert the mentioned libraries above in your HTML head tag.


Next, define a button to trigger the event ‚Save as PDF‘.


For this example, I’ve been using AngularJS, so I just added the following code in the controller.js-file.

That’s all it takes.



Wrapping it up

In my opinion, this is a good way to quickly save specific elements of a web page as an image. However, there’s a catch: the quality of the canvas object isn’t really high compared to the real representation. That’s because it doesn’t make a real screenshot. Instead, it builds the screenshot based on the information available on the page.

What about the future of these libraries? A glance at the Google statistics doesn’t yield a clear view. On the one hand, both libraries are relatively unpopular. But on the other hand, both libraries increase their level of awareness year by year. Judging by this measure, choosing these libraries probably is a good choice.


Alle Beiträge von Julius Kaiser

B.Sc.-Wi.-Ing. (HS) - Associate Developer (BI)

Schreibe einen Kommentar