Rendering HTML5 Canvas to PDF documents using Aspose.HTML
Andriy Andruhovski Jun 4
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 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 the 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.
var imageObj = (HTMLImageElement)document.CreateElement("img"); imageObj.Src = ImageFilePath; var canvas = (HTMLCanvasElement)document.GetElementsByTagName("canvas"); canvas.Width = canvasWidth; canvas.Height = canvasHeight; var context = (ICanvasRenderingContext2D)canvas.GetContext("2d"); context.ClearRect(0, 0, canvasWidth, canvasHeight); context.DrawImage(imageObj, 0, 0); context.BeginPath(); context.LineWidth = 2.0;
p elements below
Оbtained html document we can easily convert to PDF.
You can see full example here: