DEV Community

Andriy Andruhovski for Aspose.PDF

Posted on • Updated on

Rendering HTML5 Canvas to PDF documents using Aspose.HTML

In many cases, HTML documents are used to create templates for various reports with subsequent conversion into PDF docs. The Canvas API is a powerful tool for creating images and it can also be used to place graphics in PDF documents. This API is used by writing JS-scripts that can access the canvas area through a full set of drawing functions, thus allowing for dynamically generated graphics.

Aspose.HTML supports two methods of accessing to canvas elements:

  • via JavaScript code - this is a traditional method and it is preferable when we use standard HTML docs;
  • via Aspose.HTML API - this method is more convenient for creating in-memory HTML docs;

Since the first method is very popular, we will consider only a small example of its usage.

As has been said before, we will use the Aspose.HTML API in the second method. This method has some differences from the previous, mainly because of the features of the .NET platform, but the main concept is the same.
As an example, consider the following problem: suppose that we need to generate a report for one (or several) images on which we need to mark certain regions (faces, animals, etc) and add it with text. Thus, our solution will consist of the following steps:

  • Generate a template;
  • Get details about the image (from external service);
  • Generate report as HTML document;
  • Convert HTML document to PDF one.

Step 1 is pretty straightforward:

In step 2, we will use Microsoft Cognitive Services (Face API). You may learn more about this service on Microsoft Docs. In short, we call the REST API and get the result with a set of detected faces with additional info.

Now we can add the data to report: modify canvas and add p element after the canvas. In order to modify canvas, we need to get the context of this element and make the drawing.

The resulting object from the previous step is an array, which contains rectangles, that describes face locations on the image. So, we run the loop and draw the rectangles in the manner as in JavaScript code. At the last, we add details as p elements below canvas.

Оbtained HTML document we can easily convert to PDF.

You can see full example here:

Top comments (0)