渲染选项

渲染选项为您提供对渲染设备的额外控制。每个渲染设备– PdfDeviceXpsDeviceDocDeviceImageDevice–都有自己独特的选项集,分别通过类 PdfRenderingOptionsXpsRenderingOptionsDocRenderingOptionsImageRenderingOptions来实现。你可以更改页面大小、配置页边距和颜色、设置 PDF 设备的安全密码等。自定义渲染选项对于实现所需的输出文档至关重要。例如,您可以通过调整图像质量和分辨率来减小文件大小,或者通过设置页边距和文本格式来提高可读性。

本文将通过 C# 示例介绍如何使用呈现选项自定义从 HTML 到 PDF、XPS、DOCX 和图像的呈现过程。呈现器设备将选项对象作为参数,并生成输出文档。要了解有关呈现过程的更多信息,请阅读 Rendering Device 一文。

下面演示了如何使用 PdfRenderingOptions 在将 HTML 渲染成 PDF 时自定义页面大小:

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

一般选项 – General Options

Aspose.Html.Rendering 命名空间由许多呈现器对象和相应的底层选项类组成,负责将文档呈现到 IDevice 实现中。RenderingOptions 和 CssOptions 类代表渲染选项,或者换句话说,一般渲染选项。这些选项适用于从 HTML 到 PDF、XPS、DOCX 和图像的所有呈现设备和所有呈现过程:

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.

水平和垂直分辨率

在下面的示例中,我们将展示如何控制生成图像文件的分辨率,最终影响其大小和质量:

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

下图显示了 spring.html 文件在 50 dpi 和 300 dpi 分辨率下的渲染结果:

以 50 和 300 dpi 的 PNG 格式显示的两个 spring.html 文件图像

CSS 媒体类型

CSS媒体类型是一项重要功能,它规定了文档在不同媒体上的显示方式:屏幕、纸张、盲文设备等。为样式表指定媒体类型有几种方法:通过链接样式表或通过内联:

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 支持这一功能,因此您可以通过应用相应的媒体类型和样式表,将 HTML 文档转换成屏幕上或打印时的样子。下面的示例展示了如何设置媒体类型:

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

请注意, CssOptions.MediaType的默认值是打印。这意味着文档将通过应用与打印设备相关的样式表进行转换,看起来就像在纸上打印一样(您可以使用浏览器的打印预览功能查看差异)。因此,如果您想让文档看起来像在屏幕上呈现的那样,就应该使用 MediaType.Screen

背景颜色

将基于 HTML 的文件渲染为 PDF、XPS、DOCX 或图像格式时, BackgroundColor 属性用于设置输出文档的背景颜色。默认情况下,背景颜色是透明的。不过,您可以使用 RenderingOptions 类将此属性设置为特定颜色。

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

页面设置

页面设置是一组决定打印页面布局的参数。这些参数包括从页面大小、页边距、自动调整大小到 @ 页面优先规则等所有内容。使用这组参数,你可以轻松地为每个页面设置单独的布局。

下一个示例演示了如何创建左右页面尺寸不同的 PDF 文档(见下图 (a) 中的结果可视化):

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

在某些情况下,HTML 页面的内容可能比选项定义的页面尺寸更宽。如果不想截断页面内容,可以使用 PageSetup 类的 AdjustToWidestPage 属性。下面的示例展示了如何根据内容调整页面大小(见下图 (b) 中的结果可视化):

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

文本 “两张图片–每页自定义布局的结果和根据内容调整页面大小的结果”

要了解有关渲染过程的更多信息,请阅读 渲染设备 一文。

如果您想了解如何使用呈现选项将文档页面大小调整为内容大小,反之亦然,请访问文章 [如何在 HTML 转换过程中调整文档大小?

PDF 渲染选项 – PdfRenderingOptions

除了常规选项外, PdfRenderingOptions类还支持一些特定参数,如 JpegQuality、DocumentInfo、Encryption 和 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.

FormFieldBehaviour “属性用于指定 PDF 文档中表单域的行为。如需了解 PDF 文件扁平化的含义以及如何使用 Aspose.HTML for .NET 库进行扁平化,请参阅 Flatten PDF 一文。

以下 C# 代码演示了如何使用 PdfRenderingOptions 类为 PDF 输出文件添加加密功能:

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

上例展示了如何创建一个新的 PdfRenderingOptions 实例,并为 PDF 输出文件设置加密选项。为此,你应该使用 PdfEncryptionInfo(userPassword, ownerPassword, permissions, encryptionAlgorithm) 构造函数创建一个 PdfEncryptionInfo 对象,该对象定义了 PDF 文件的加密设置。构造函数需要四个参数:<br

图像渲染选项 – ImageRenderingOptions

ImageRenderingOptions 类支持所有常规选项,并允许您配置特定选项,例如抗锯齿、文本渲染配置、图像格式选择和图像压缩。

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.

让我们来看看如何使用专门的 ImageRenderingOptions 对象来配置图像的渲染质量。下面的示例演示了如何更改生成图像的分辨率和抗锯齿。

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

XPS 渲染选项 – XpsRenderingOptions

我们的程序库生成的 XPS 文件没有任何特定参数。XpsRenderingOptions 的所有参数都继承自基础 RenderingOptions类,并在此处 中进行了说明。

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

DOC 渲染选项 – DocRenderingOptions

DocRenderingOptions 类支持所有常规选项,并允许您自定义输出文件的 FontEmbeddingRuleDocumentFormat 属性。

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.

下面的示例显示了如何通过设置页面大小和字体嵌入规则来自定义输出文档的呈现选项:

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

Aspose.HTML 提供免费的在线 转换器,可将 HTML、XHTML、MHTML、EPUB、XML 和 Markdown 文件转换为一系列流行格式。你可以轻松地将 HTML 文档转换为 PDF、XPS、DOCX、JPG、PNG、GIF、TIFF 等格式。只需选择文件,选择要转换的格式,就大功告成了。最重要的是,它完全免费!

文本 “HTML 网络应用程序”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.