Renderers – Render HTML, MHTML, EPUB, and SVG in C#

Contents
[ Hide Show ]

Use renderers directly when Document.RenderTo() is not enough. HtmlRenderer, SvgRenderer, MhtmlRenderer, and EpubRenderer can render source-specific documents to an output device, merge multiple sources, and control rendering timeout.

Renderers

The Aspose.Html.Rendering namespace consists of numerous renderer objects and appropriate low-level options classes, which are responsible for rendering documents into IDevice implementation. Aspose.HTML for .NET API provides the following realization of renderers: HtmlRenderer, SvgRenderer, MhtmlRenderer, and EpubRenderer, which are used to render HTML, SVG, MHTML, and EPUB documents, respectively.

While the RenderTo() method of the Document class gives you the ability to send a single document to the output rendering device, using the Renderer instances directly, you can send multiple files at once. You can merge HTML, MHTML, EPUB, and SVG documents and apply rendering options to control the output file.

The current article describes supported scenarios of HTML-based file conversion & merging to other popular formats using Render() methods of the Renderer class.

HtmlRenderer

Usage of the HtmlRenderer class to render HTML files to other popular formats – is one more way to convert HTML by customizing the rendering options and controlling the rendering process’s output. Let’s look at using the HtmlRenderer class to render HTML to PDF with custom rendering options:

  1. Initialize an HTML document. Use one of the HTMLDocument() constructors to create an HTMLDocument instance.
  2. Create a new HtmlRenderer object.
  3. Create the instance of the PdfRenderingOptions and set custom options for the output PDF document. In the example, we specify the AnyPage property of the PageSetup class that sets a new Page object with a page size of 600 pixels by 200 pixels and the Encryption property that identifies the user and owner passwords, allowed permissions, and encryption algorithm for the output PDF file.
  4. Use PdfDevice(options, savePath) constructor to create an object of the PdfDevice class.
  5. And finally, call the Render(device, document) method to render the HTML document to the output PDF file with the specified rendering options.
 1// Render HTML to PDF with custom page settings using C#
 2
 3// Prepare a path to a source HTML file
 4string documentPath = Path.Combine(DataDir, "file.html");
 5
 6// Initialize an HTML document from the file
 7using HTMLDocument document = new HTMLDocument(documentPath);
 8
 9// Create an instance of HTML Renderer
10using HtmlRenderer renderer = new HtmlRenderer();
11
12// Prepare a path to save the converted file 
13string savePath = Path.Combine(OutputDir, "convert-html-options.pdf");
14
15// Create the instance of Rendering Options and set a custom page-size
16PdfRenderingOptions options = new PdfRenderingOptions();
17options.PageSetup.AnyPage = new Page(new Size(600, 200));
18options.Encryption = new PdfEncryptionInfo(
19       "user_pwd",
20       "owner_pwd",
21       PdfPermissions.PrintDocument,
22       PdfEncryptionAlgorithm.RC4_128);
23
24// Create an instance of PDF device
25using PdfDevice device = new PdfDevice(options, savePath);
26
27// Render HTML to PDF
28renderer.Render(device, document);

Rendering options give you additional control over the rendering process. To learn more about them, please read the Rendering options article.

To learn more about rendering process, please read the Rendering Device article.

If you are interested in how to use rendering options to resize document pages to the size of the content and vice versa, please visit the article How to Resize Document During Conversion from HTML?

SvgRenderer

The SvgRenderer allows you to render SVG files to other file formats, such as PDF, XPS, DOCX, and image formats. With this, you can customize the output file using various rendering options. The following example demonstrates how to use SvgRenderer class to render SVG to PDF with a custom page size specifying:

  1. Initialize an SVG document. Use one of the SVGDocument() constructors to create an SVGDocument instance.
  2. Create a new SvgRenderer object.
  3. Create an instance of the PdfRenderingOptions and set custom options for the output PDF document. In the example, we specify the PageSetup.AnyPage property that sets a new Page object with a page size of 600x500 pixels.
  4. Use the PdfDevice(options, savePath) constructor to create an object of the PdfDevice class.
  5. And finally, call the Render(device, document) method to render the SVG document to the output PDF file with the specified rendering options.
 1// Render SVG to PDF using C#
 2
 3// Initialize an SVG document from the file
 4using SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
 5
 6// Create an instance of SVG Renderer
 7using SvgRenderer renderer = new SvgRenderer();
 8
 9// Prepare a path to save the converted file 
10string savePath = Path.Combine(OutputDir, "rendering-svg.pdf");
11
12// Create the instance of Rendering Options and set a custom page-size
13PdfRenderingOptions options = new PdfRenderingOptions();
14options.PageSetup.AnyPage = new Page(new Size(600, 500));
15
16// Create an instance of the Pdfdevice class
17using PdfDevice device = new PdfDevice(options, savePath);
18
19// Render SVG to PDF
20renderer.Render(device, document);

MhtmlRenderer

The following example demonstrates how to convert MHTML to PDF with the rendering options specifying using the MhtmlRenderer class:

  1. Open an existing MHTML document.
  2. Create an instance of MhtmlRenderer using the MhtmlRenderer() constructor.
  3. Initialize the PdfRenderingOptions class and set rendering options.
  4. Create an instance of the PdfDevice class.
  5. Call the Render(device, stream) method to render MHTML to PDF.
 1// Convert MHTML to PDF with custom page settings using C#
 2
 3// Open an existing MHTML file for reading
 4using FileStream stream = File.OpenRead(DataDir + "sample.mht");
 5
 6// Create an instance of MHTML Renderer
 7using MhtmlRenderer renderer = new MhtmlRenderer();
 8
 9// Prepare a path to save the converted file 
10string savePath = Path.Combine(OutputDir, "convert-mhtml-options.pdf");
11
12// Create the instance of Rendering Options and set a custom page-size and background color
13PdfRenderingOptions options = new PdfRenderingOptions();
14options.PageSetup.AnyPage = new Page(new Size(600, 200));
15options.BackgroundColor = System.Drawing.Color.Azure;
16
17// Create an instance of PDF device
18using PdfDevice device = new PdfDevice(options, savePath);
19
20// Convert MHTML to PDF
21renderer.Render(device, stream);

EpubRenderer

The EpubRenderer class allows you to convert EPUB files to other formats such as PDF, XPS, DOCX, and images. The following C# examples shows how to convert EPUB to DOCX with a custom page size setting:

  1. Open an existing EPUB file.
  2. Create an instance of EpubRenderer class.
  3. Initialize the DocRenderingOptions class and set rendering options.
  4. Create an instance of the DocDevice class.
  5. Call the Render(device, stream) method to render EPUB to DOCX.
 1// Convert EPUB to DOCX with custom page size using C#
 2
 3// Open an existing EPUB file for reading
 4using FileStream stream = File.OpenRead(DataDir + "input.epub");
 5
 6// Create an instance of EPUB Renderer
 7using EpubRenderer renderer = new EpubRenderer();
 8
 9// Prepare a path to save the converted file 
10string savePath = Path.Combine(OutputDir, "convert-epub-options.docx");
11
12// Create the instance of Rendering Options and set a custom page-size
13DocRenderingOptions options = new DocRenderingOptions();
14options.PageSetup.AnyPage = new Page(new Size(800, 400));
15
16// Create an instance of the DocDevice class
17using DocDevice device = new DocDevice(options, savePath);
18
19// Render EPUB to DOCX
20renderer.Render(device, stream);

Merge HTML

Aspose.HTML for .NET API provides the Renderer class for rendering and merging HTML, MHTML, EPUB, and SVG documents to popular formats. While the RenderTo() method gives you the ability to send a single document to the output rendering device, using the Renderer instances directly, you can send multiple files at once. HtmlRenderer, SvgRenderer, MhtmlRenderer, and EpubRenderer can merge HTML, SVG, MHTML, and EPUB documents, respectively. The next example demonstrates how to use HtmlRenderer to render multiple HTML documents.

To merge HTML documents:

  1. Load the HTML documents that should be rendered into one output file.
  2. Create the target device, such as PdfDevice, with the output path.
  3. Create an HtmlRenderer instance.
  4. Pass the device and documents to renderer.Render().
  5. Save the merged result as one PDF document.
 1// Merge HTML to PDF using C#
 2
 3// Prepare HTML code
 4string code1 = @"<br><span style='color: green'>Hello, World!!</span>";
 5string code2 = @"<br><span style='color: blue'>Hello, World!!</span>";
 6string code3 = @"<br><span style='color: red'>Hello, World!!</span>";
 7
 8// Create three HTML documents to merge later
 9using HTMLDocument document1 = new HTMLDocument(code1, ".");
10using HTMLDocument document2 = new HTMLDocument(code2, ".");
11using HTMLDocument document3 = new HTMLDocument(code3, ".");
12
13// Create an instance of HTML Renderer
14using HtmlRenderer renderer = new HtmlRenderer();
15
16// Prepare a path to save the converted file 
17string savePath = Path.Combine(OutputDir, "merge-html.pdf");
18
19// Create an instance of PDF device
20using PdfDevice device = new PdfDevice(savePath);
21
22// Merge all HTML documents into PDF
23renderer.Render(device, document1, document2, document3);

Set Timeout

One more important feature that is available for renderers is timeout. You can use it to specify how long you are ready to wait for internal processes related to a document lifecycle to be completed, such as resource loading and active timers. You can specify an infinite waiting period, but if the document contains a script with an endless loop, the render operation may wait indefinitely.

To render with a timeout:

  1. Create or load the source document.
  2. Create the renderer and output device.
  3. Choose a TimeSpan timeout value.
  4. Call renderer.Render(device, timeout, document).
  5. Handle the partially rendered output if the timeout is reached.

The example below demonstrates how to use the timeout parameter:

 1// Render HTML to PDF with timeout settings using C#
 2
 3// Prepare HTML code
 4string code = @"
 5<script>
 6    var count = 0;
 7    setInterval(function()
 8        {
 9            var element = document.createElement('div');
10            var message = (++count) + '. ' + 'Hello, World!! I know how to use Renderers!';
11            var text = document.createTextNode(message);
12            element.appendChild(text);
13            document.body.appendChild(element);
14        }, 1000);
15</script>";
16
17// Initialize an HTML document based on prepared HTML code
18using HTMLDocument document = new HTMLDocument(code, ".");
19
20// Create an instance of HTML Renderer
21using HtmlRenderer renderer = new HtmlRenderer();
22
23// Prepare a path to save the converted file 
24string savePath = Path.Combine(OutputDir, "output-timeout.pdf");
25
26// Create an instance of the PdfDevice class
27using PdfDevice device = new PdfDevice(savePath);
28
29// Render HTML to PDF
30renderer.Render(device, TimeSpan.FromSeconds(5), document);

In this example, we create an HTML document that adds a new <div> element every second with a sequential number and the message “Hello, World!!” We use the TimeSpan parameter in the Render(device, timeout, document) method to set timeout. This setting specifies the maximum time the renderer will spend rendering the document. In this case, the total time is set to 5 seconds. If the renderer has not generated a document within the specified time, it will stop and render a partially rendered document. Running this example, you will get a document with five lines of “Hello, World!! I know how to use Renderers!” message, as follows:

Five lines of ‘Hello, World!! I know how to use Renderers!’

Common Renderer Mistakes

Related Rendering Guides

The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.

Free Online Converters