Rendering Options | C#

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 during render HTML to PDF:

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

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

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Rendering.Pdf;
 4...
 5    // Prepare path to a source HTML file
 6    string documentPath = Path.Combine(DataDir, "spring.html");
 7
 8    // Prepare path for converted file saving 
 9    string savePath = Path.Combine(OutputDir, "spring.pdf");
10
11    // Create an instance of HTML document
12    using var document = new HTMLDocument(documentPath);
13
14    // Initialize options with 'cyan' as a background-color
15    var options = new PdfRenderingOptions()
16    {
17        BackgroundColor = System.Drawing.Color.Azure
18    };
19
20    // Create an instance of PDF device
21    using var device = new PdfDevice(options, savePath);
22
23    // Render HTML to PDF
24    document.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):

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

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

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Rendering.Pdf;
 4using Aspose.Html.Rendering.Pdf.Encryption;
 5...
 6    // Prepare a path to a source HTML file
 7    string documentPath = Path.Combine(DataDir, "document.html");
 8
 9    // Initialize the HTML document from the file
10    using var document = new HTMLDocument(documentPath);
11
12    // Create the instance of Rendering Options
13    var options = new PdfRenderingOptions();
14
15    // Set the permissions to the file
16    options.Encryption = new PdfEncryptionInfo(
17            "user_pwd",
18            "owner_pwd",
19            PdfPermissions.PrintDocument,
20            PdfEncryptionAlgorithm.RC4_128);
21
22    // Prepare path for converted file saving 
23    string savePath = Path.Combine(OutputDir, "output-options.pdf");
24
25    // Create an instance of the PdfDevice and specify options and output file
26    using var device = new PdfDevice(options, savePath);
27
28    // Render HTML to PDF
29    document.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 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.
SmoothingModeThis property sets the rendering quality for this image. Available values are Invalid, Default, HighSpeed, HighQuality, None, and AntiAlias.
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.

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

XPS 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.

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

DOCX 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:

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Rendering.Doc;
 4...
 5    // Prepare a path to a source HTML file
 6    string documentPath = Path.Combine(DataDir, "document.html");
 7
 8    // Initialize the HTML document from the file
 9    using var document = new HTMLDocument(documentPath);
10
11    // Create an instance of Rendering Options and set a custom page size
12    var options = new DocRenderingOptions();
13    options.PageSetup.AnyPage = new Page(new Size(Length.FromInches(6), Length.FromInches(3)));
14    options.FontEmbeddingRule = (FontEmbeddingRule.Full);
15
16    // Prepare path for converted file saving 
17    string savePath = Path.Combine(OutputDir, "document-options.docx");
18
19    // Create an instance of the DocDevice and specify options and output file
20    using var device = new DocDevice(options, savePath);
21
22    // Render HTML to DOCX
23    document.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 “Banner HTML Web Applications”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.