Rendering Options

Rendering Options gives you additional control over the rendering device. Every rendering device – PdfDevice, XpsDevice, DocDevice, and ImageDevice has its own unique set of options implemented with classes PdfRenderingOptions, XpsRenderingOptions, DocRenderingOptions, and ImageRenderingOptions respectively. You can change the page size, configure margins and colors, set a security password in case of a PDF device, etc. Customizing rendering options is essential to achieve the desired output document. For example, you can reduce the file size by adjusting image quality and resolution or improve readability by setting page margins and text formatting.

In this article, we describe in C# examples how to use rendering options to customize the rendering process from HTML to PDF, XPS, DOCX, and Images. A renderer device takes an options object as a parameter and represents an output document. To learn more, please read the Rendering Device article.

Following is a demonstration of how to use PdfRenderingOptions to customize the page size when rendering HTML to PDF:

 1var code = @"<span>Hello, World!!</span>";
 2
 3// Initialize an HTML document from HTML code
 4using var document = new HTMLDocument(code, ".");
 5
 6// Create an instance of PdfRenderingOptions and set a custom page size
 7var options = new PdfRenderingOptions()
 8{
 9    PageSetup =
10        {
11            AnyPage = new Page(new Size(Length.FromInches(4),Length.FromInches(2)))
12        }
13};
14
15// Prepare a path to save the converted file 
16string savePath = Path.Combine(OutputDir, "file-with-custom-page-size.pdf");            
17
18// Create an instance of the PdfDevice and specify the options and output file to render
19using var device = new PdfDevice(options, savePath);
20
21// Render HTML to PDF
22document.RenderTo(device);

General Options

The Aspose.Html.Rendering namespace consists of numerous renderer objects and appropriate low-level options classes responsible for rendering documents into IDevice implementation. The RenderingOptions and CssOptions classes represent rendering options, or in other words, general rendering options. These options are valid for all rendering devices and all rendering processes from HTML to PDF, XPS, DOCX, and Images:

PropertyDescription
PageSetupThis property gets a page setup object and uses it for configuration output page-set.
CssGets a CssOptions object which is used for configuration of CSS properties processing.
BackgroundColorThis property sets the color that will fill the background of every page. By default, this property is Transparent.
HorizontalResolutionSets horizontal resolution for output images in pixels per inch. The default value is 300 dpi.
VerticalResolutionSets vertical resolution for output images in pixels per inch. The default value is 300 dpi.
MediaTypeSets MediaType which will be used for media queries resolution during rendering. Default value is Print.

Horizontal and Vertical Resolution

In the following example, we will show how we can control the resolution of the resulting image file, ultimately affecting its size and quality:

 1// Prepare a path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "spring.html");            
 3
 4// Create an instance of HTML document
 5using var document = new HTMLDocument(documentPath);
 6
 7// Prepare path to save output file 
 8string savePath1 = Path.Combine(OutputDir, "output_resolution_50.png");
 9string savePath2 = Path.Combine(OutputDir, "output_resolution_300.png");
10
11// Create options for low-resolution screens
12    var options1 = new ImageRenderingOptions()
13    {
14        HorizontalResolution = 50,
15        VerticalResolution = 50
16    };
17
18// Create an instance of Image device
19using var device1 = new ImageDevice(options1, savePath1);
20
21// Render HTML to PNG
22document.RenderTo(device1);
23
24
25// Create options for high-resolution screens
26var options2 = new ImageRenderingOptions()
27{
28    HorizontalResolution = 300,
29    VerticalResolution = 300
30};
31
32// Create an instance of Image device
33using var device2 = new ImageDevice(options2, savePath2);
34
35// Render HTML to PNG
36document.RenderTo(device2);

The next picture shows the result of the rendering of the spring.html file with 50 dpi and 300 dpi resolutions:

Two images of the spring.html file rendered to PNG format at 50 and 300 dpi

CSS Media Type

CSS media-type is an important feature that specifies how a document will be presented on different media: on the screen, on paper, with a braille device, etc. There are a few ways to specify media-type for a style sheet, via linked style sheets or, via inlining:

Linked Style Sheet

1 <link rel="stylesheet" type="text/css" media="print" href="style.css">

Inline Style Sheet

1<style type="text/css">
2@media print {
3  body{ color: #000000; }
4}
5</style>

Aspose.HTML API supports this feature, so you can convert HTML documents as they look on screen or on print with applying the corresponded media types and style sheets. Following example shows how to set up the media type:

1// Create an option class
2var options = new PdfRenderingOptions();
3
4// Set the 'screen' media-type
5options.Css.MediaType = MediaType.Screen;

Please note that the default value of the CssOptions.MediaType is Print. It means that the document will be converted by applying style sheets related to the printing device and looks like on paper (you can use print preview of your browser to see the difference). So if you want the document to look the way it is rendered on screen, you should use MediaType.Screen.

Background Color

The BackgroundColor property is used to set the background color of the output document when rendering HTML-based files to PDF, XPS, DOCX, or image formats. By default, the background color is transparent. However, you can set this property to a specific color using the RenderingOptions class.

 1// Prepare path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "spring.html");
 3
 4// Prepare a path to save the converted file 
 5string savePath = Path.Combine(OutputDir, "spring.pdf");
 6
 7// Create an instance of HTML document
 8using var document = new HTMLDocument(documentPath);
 9
10// Initialize options with 'Azure' as a background-color
11var options = new PdfRenderingOptions()
12{
13    BackgroundColor = System.Drawing.Color.Azure
14};
15
16// Create an instance of PDF device
17using var device = new PdfDevice(options, savePath);
18
19// Render HTML to PDF
20document.RenderTo(device);

Page Setup

The page setup is a set of parameters that determine the layout of a printed page. Those parameters include everything from the page size, margins, and auto-resizing to @page priority rules. You can easily set up an individual layout for every page using this set of parameters.

The next example demonstrates how to create a PDF document with different page sizes for the left and right pages (see the result visualization in figure (a) below):

 1// Prepare HTML code
 2var code = @"<style>div { page-break-after: always; }</style>
 3<div>First Page</div>
 4<div>Second Page</div>
 5<div>Third Page</div>
 6<div>Fourth Page</div>";
 7
 8// Initialize an HTML document from the HTML code
 9using var document = new HTMLDocument(code, ".");
10
11// Create the instance of Rendering Options and set a custom page size
12var options = new PdfRenderingOptions();
13options.PageSetup.SetLeftRightPage(
14    new Page(new Size(400, 150)),
15    new Page(new Size(400, 50))
16);
17
18// Prepare a path to save the converted file 
19string savePath = Path.Combine(OutputDir, "output-custom-page-size.pdf");
20
21// Create the PDF Device and specify options and output file
22using var device = new PdfDevice(options, savePath);
23
24// Render HTML to PDF
25document.RenderTo(device);

In some cases, the content of the HTML page could be wider than the page-size defined with options. If you don’t want to cut off the page content, you can try the AdjustToWidestPage property of the PageSetup class. The following example shows how to adjust the page size to the content (see the result visualization in figure (b) below):

 1// Prepare HTML code
 2var code = @"<style>
 3    div { page-break-after: always; }
 4</style>
 5<div style='border: 1px solid red; width: 300px'>First Page</div>
 6<div style='border: 1px solid red; width: 500px'>Second Page</div>";
 7
 8// Initialize an HTML document from the HTML code
 9using var document = new HTMLDocument(code, ".");
10
11// Create the instance of Rendering Options and set a custom page-size
12var options = new PdfRenderingOptions();
13options.PageSetup.AnyPage = new Page(new Size(400, 200));
14
15// Enable auto-adjusting for the page size
16options.PageSetup.AdjustToWidestPage = true;
17
18// Prepare a path to save the converted file 
19string savePath = Path.Combine(OutputDir, "output-widest-page-size.pdf");
20
21// Create the PdfDevice and specify options and output file
22using var device = new PdfDevice(options, savePath);
23
24// Render HTML to PDF
25document.RenderTo(device);

Text “Two images – the result of customizing the layout for each page and the result of adjusting the page size to content”

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?

PDF Rendering Options

The PdfRenderingOptions class, along with general options, supports some specific parameters, such as JpegQuality, DocumentInfo, Encryption, and FormFieldBehaviour.

PropertyDescription
JpegQualitySpecifies the quality of JPEG compression for images. The default value is 95.
DocumentInfoThis property contains information about the output PDF document.
EncryptionThis property gets or sets encryption details. If it is not set, then no encryption will be performed.
FormFieldBehaviourThis property specifies the behavior of form fields in the output PDF document.

The FormFieldBehaviour property is used to specify the behavior of form fields in a PDF document. To learn what it means to flatten a PDF file and how to do it using the Aspose.HTML for .NET library, please see the Flatten PDF article.

The following C# code demonstrates how to add encryption to a PDF output file using the PdfRenderingOptions class:

 1// Prepare a path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "document.html");
 3
 4// Initialize the HTML document from the file
 5using var document = new HTMLDocument(documentPath);
 6
 7// Create the instance of Rendering Options
 8var options = new PdfRenderingOptions();
 9
10// Set the permissions to the file
11options.Encryption = new PdfEncryptionInfo(
12        "user_pwd",
13        "owner_pwd",
14        PdfPermissions.PrintDocument,
15        PdfEncryptionAlgorithm.RC4_128);
16
17// Prepare a path to save the converted file 
18string savePath = Path.Combine(OutputDir, "output-options.pdf");
19
20// Create an instance of the PdfDevice and specify options and output file
21using var device = new PdfDevice(options, savePath);
22
23// Render HTML to PDF
24document.RenderTo(device);

The example above shows how to create a new PdfRenderingOptions instance and set encryption options for a PDF output file. For this, you should use the PdfEncryptionInfo(userPassword, ownerPassword, permissions, encryptionAlgorithm) constructor to create a PdfEncryptionInfo object, which defines the encryption settings for the PDF file. The constructor takes four parameters:

Image Rendering Options

The ImageRenderingOptions class supports all general options and allows you to configure specific options, such as anti-aliasing (dithering), text rendering configuration, image formats, and image compression.

PropertyDescription
CompressionSets Tagged Image File Format (TIFF) Compression. By default, this property is LZW.
FormatSets the ImageFormat (JPG, PNG, BMP, TIFF, or GIF). By default, this property is PNG.
UseAntialiasingThis property sets the rendering quality for the image.
TextGets a TextOptions object which is used for configuration of text rendering.

Let’s consider how to use a specialized ImageRenderingOptions object to configure the rendering quality for the image. The following example demonstrates how to change resolution and antialiasing for the resulting image.

 1// Prepare a path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "color.html");
 3
 4// Initialize the HTML document from the file
 5using var document = new HTMLDocument(documentPath);
 6
 7// Create an instance of Rendering Options
 8var options = new ImageRenderingOptions(ImageFormat.Jpeg)
 9{
10    // Disable smoothing mode
11    UseAntialiasing = false,
12
13    // Set the image resolution as 75 dpi
14    VerticalResolution = Resolution.FromDotsPerInch(75),
15    HorizontalResolution = Resolution.FromDotsPerInch(75),
16};
17
18// Prepare a path to save the converted file 
19string savePath = Path.Combine(OutputDir, "color-options.jpg");
20
21// Create an instance of the ImageDevice and specify options and output file
22using var device = new ImageDevice(options, savePath);
23
24// Render HTML to JPG
25document.RenderTo(device);

XPS Rendering Options

XPS files generated by our library do not have any specific parameters. All parameters of XpsRenderingOptions are inherited from the base RenderingOptions class and described here.

 1// Prepare a path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "document.html");
 3
 4// Initialize the HTML document from the file
 5using var document = new HTMLDocument(documentPath);
 6
 7// Create an instance of Rendering Options
 8var options = new XpsRenderingOptions();
 9options.PageSetup.AnyPage = new Page(new Size(Length.FromInches(5), Length.FromInches(2)));
10
11// Prepare a path to save the converted file 
12string savePath = Path.Combine(OutputDir, "document-options.xps");
13
14// Create an instance of the XpsDevice and specify options and output file
15using var device = new XpsDevice(options, savePath);
16
17// Render HTML to XPS
18document.RenderTo(device);

DOC Rendering Options

The DocRenderingOptions class supports all general options and allows you to customize FontEmbeddingRule and DocumentFormat properties for the output file.

PropertyDescription
FontEmbeddingRuleThis property gets or sets the font embedding rule. Available values are Full and None. The default value is None.
DocumentFormatThis property gets or sets the file format of the output document. The default value is DOCX.

The following example shows how to customize the rendering options for output documents by setting the page size and font embedding rule:

 1// Prepare a path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "nature.html");
 3
 4// Initialize the HTML document from the file
 5using var document = new HTMLDocument(documentPath);
 6
 7// Create an instance of Rendering Options and set a custom page size
 8var options = new DocRenderingOptions();
 9options.PageSetup.AnyPage = new Page(new Size(Length.FromInches(8), Length.FromInches(10)));
10options.FontEmbeddingRule = (FontEmbeddingRule.Full);
11
12// Prepare a path to save the converted file 
13string savePath = Path.Combine(OutputDir, "nature-options.docx");
14
15// Create an instance of the DocDevice and specify options and output file
16using var device = new DocDevice(options, savePath);
17
18// Render HTML to DOCX
19document.RenderTo(device);

You can download the complete C# examples and data files from GitHub.

Aspose.HTML offers free online Converters that can convert HTML, XHTML, MHTML, EPUB, XML, and Markdown files to a range of popular formats. You can easily convert your HTML-based documents to PDF, XPS, DOCX, JPG, PNG, GIF, TIFF, and others. Just select a file, choose the format to convert, and you’re done. Best of all, it’s completely free!

Text “HTML Web Applications”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.