Параметры рендеринга – С#
Параметры рендеринга дают вам дополнительный контроль над устройством рендеринга. Каждое устройство рендеринга – PdfDevice, XpsDevice, DocDevice, и ImageDevice имеет собственный уникальный набор параметров, реализованных с помощью классов PdfRenderingOptions, XpsRenderingOptions, DocRenderingOptions, и ImageRenderingOptions соответственно. Вы можете изменить размер страницы, настроить поля и цвета, установить пароль безопасности в случае устройства PDF и т. д. Настройка параметров рендеринга необходима для получения желаемого выходного документа. Например, вы можете уменьшить размер файла, настроив качество и разрешение изображения, или улучшить читаемость, настроив поля страницы и форматирование текста.
В этой статье мы опишем на примерах C#, как использовать параметры рендеринга для настройки процесса рендеринга из HTML в PDF, XPS, DOCX и изображения. Устройство визуализации принимает объект опций в качестве параметра и представляет выходной документ. Чтобы узнать больше, обратитесь к статье Устройство рендеринга.
Ниже показано, как использовать 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);
Общие Hастройки
Пространство имен Aspose.Html.Rendering состоит из многочисленных объектов рендеринга и соответствующих низкоуровневых классов опций, отвечающих за рендеринг документов в IDevice реализации. RenderingOptions и CssOptions представляют общие параметры рендеринга. Эти параметры действительны для всех устройств рендеринга и всех процессов рендеринга HTML в PDF, XPS, DOCX и изображения:
Property | Description |
---|---|
PageSetup | This property gets a page setup object and uses it for configuration output page-set. |
Css | Gets a CssOptions object which is used for configuration of CSS properties processing. |
BackgroundColor | This property sets the color that will fill the background of every page. By default, this property is Transparent. |
HorizontalResolution | Sets horizontal resolution for output images in pixels per inch. The default value is 300 dpi. |
VerticalResolution | Sets vertical resolution for output images in pixels per inch. The default value is 300 dpi. |
MediaType | Sets 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:
CSS Media Type
CSS media-type – важная функция, которая определяет, как документ будет представлен на разных носителях: на экране, на бумаге, с помощью устройства Брайля и т. д. Существует несколько способов указать madia-type для таблицы стилей, через связанные таблицы стилей или через встраивание:
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 является Print. Это означает, что документ будет преобразован с применением таблиц стилей, относящихся к печатающему устройству, и выглядит как на бумаге (вы можете использовать предварительный просмотр печати в браузере, чтобы увидеть разницу). Поэтому, если вы хотите, чтобы документ выглядел так, как он отображается на экране, вы должны использовать MediaType.Screen.
Цвет фона – Background Color
Свойство BackgroundColor используется для установки цвета фона выходного документа при преобразовании HTML-файлов в формат PDF, XPS, DOCX или форматы изображений. По умолчанию цвет фона прозрачный. Однако вы можете установить для этого свойства определенный цвет с помощью класса 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);
Параметры страницы – Page Setup
Параметры страницы – это набор параметров, определяющих макет печатной страницы. Эти параметры включают в себя все, от размера страницы, полей и автоматического изменения размера до правил приоритета @page. Используя этот набор параметров, вы можете легко настроить индивидуальный макет для каждой страницы.
В следующем примере показано, как создать 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);
В некоторых случаях содержимое HTML-страницы может быть шире, чем размер страницы, определенный параметрами. Если вы не хотите обрезать содержимое страницы, вы можете попробовать свойство AdjustToWidestPage класса PageSetup. В следующем примере показано, как настроить размер страницы в соответствии с содержимым (см. визуализацию результата на рисунке (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 Options
Класс PdfRenderingOptions, наряду с общими параметрами, поддерживает некоторые специфические параметры, такие как JpegQuality, DocumentInfo, Encryption и FormFieldBehaviour.
Property | Description |
---|---|
JpegQuality | Specifies the quality of JPEG compression for images. The default value is 95. |
DocumentInfo | This property contains information about the output PDF document. |
Encryption | This property gets or sets encryption details. If it is not set, then no encryption will be performed. |
FormFieldBehaviour | This property specifies the behavior of form fields in the output PDF document. |
Свойство FormFieldBehaviour используется для указания поведения полей формы в документе PDF. Чтобы узнать, что означает сведение файла PDF и как это сделать с помощью библиотеки Aspose.HTML for .NET, обратитесь к статье Flatten PDF.
Следующий код C# демонстрирует, как добавить шифрование в выходной файл PDF с помощью класса PdfRenderingOptions
:
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. Конструктор принимает четыре параметра:
userPassword
иownerPassword
, необходимые для открытия и работы с файлом PDF;permissions
– набор разрешенных разрешений для файла PDF. В этом случае указываетсяPdfPermissions.PrintDocument
, что позволяет пользователю распечатать документ;encryptionAlgorithm
– алгоритм шифрования, используемый для защиты файла PDF. В этом случае используетсяPdfEncryptionAlgorithm.RC4_128
, который представляет собой 128-битный алгоритм шифрования RC4.
Image Options
Класс ImageRenderingOptions поддерживает все общие параметры и позволяет настраивать определенные параметры, например сглаживание, конфигурацию рендеринга текста, выбор формата и сжатие изображений.
Property | Description |
---|---|
Compression | Sets Tagged Image File Format (TIFF) Compression. By default, this property is LZW. |
Format | Sets the ImageFormat (JPG, PNG, BMP, TIFF, or GIF). By default, this property is PNG. |
UseAntialiasing | This property sets the rendering quality for this image. |
Text | Gets 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 Options
Файлы 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);
DOCX Options
Класс DocRenderingOptions поддерживает все общие параметры и позволяет настраивать свойства FontEmbeddingRule и DocumentFormat для выходной файл.
Property | Description |
---|---|
FontEmbeddingRule | This property gets or sets the font embedding rule. Available values are Full and None. The default value is None. |
DocumentFormat | This 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);
Вы можете скачать полные примеры C# и файлы данных с GitHub.
Aspose.HTML предлагает бесплатные онлайн Конвертеры, которые могут преобразовывать файлы HTML, XHTML, MHTML, EPUB, XML и Markdown в ряд популярных форматов. Вы можете легко конвертировать HTML-документы в форматы PDF, XPS, DOCX, JPG, PNG, GIF, TIFF и другие форматы. Просто выберите файл, выберите формат для преобразования, и все готово. Лучше всего то, что это совершенно бесплатно!