Capture & Embed Image in PDF using Html2canvas

1 min read

I recently faced a situation where I needed to capture a part of a HTML page and embed it in a PDF file.
I am using the wkhtmltopdf library for one of my projects, where we needed to export a visualization rendered using the visjs JS plugin as a PDF. While using this library we were facing severe performance issues because of the complexity of the timeline generated by visjs.
Screen Shot 2015-07-01 at 8.57.29 pm
After trying few things out, we settled with the idea of taking a snapshot of the timeline and embedding that image in the PDF file. This approach saved us a lot of time and worked like a charm and also improved the speed while generating the PDF.

html2canvas:

For this work I used html2canvas which is a JS library that helps to take screenshots of complete webpages or capture part of a webpage.
Using html2canvas I captured a part of a webpage which is the timeline rendered by visjs and pushed it to the server via an Ajax request and later while creating the PDF I embedded the image in the HTML that’s supplied to wkhtmltopdf instead of directly rendering the timeline using visjs library.

How it works?

html2canvs doesn’t actually take screenshots, It gathers information on all the elements in the page, which it then uses to build a representation of the page. So the screenshot may not be accurate and its clearly mentioned in their website itself. But in my case it worked fine may because visjs uses all CSS which this plugin understands very well.
Here is the screenshot taken using html2canvas:
Screen Shot 2015-07-01 at 7.57.24 pm

Code snippet

Related posts:

One Reply to “Capture & Embed Image in PDF using Html2canvas”

Leave a Reply

Your email address will not be published. Required fields are marked *