Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Параметры рендеринга обеспечивают детальный контроль над тем, как устройство рендеринга обрабатывает содержимое. Каждое устройство – PdfDevice, XpsDevice, DocDevice и ImageDevice – имеет свой класс опций: PdfRenderingOptions, XpsRenderingOptions, DocRenderingOptions и ImageRenderingOptions. С помощью этих опций вы можете настроить размер страницы, поля и цвета, а также применить настройки, специфичные для конкретного устройства, например, добавить пароль безопасности к PDF-файлам. Настройка очень важна для достижения желаемых результатов, будь то уменьшение размера файла за счет регулировки качества и разрешения изображений или повышение удобочитаемости за счет оптимизации макета страницы и форматирования текста.
В этой статье рассматриваются опции рендеринга в Aspose.HTML for Python via .NET, показывающие, как настраивать преобразование HTML-контента в выходные форматы, такие как PDF, XPS, DOCX и изображения. Эти параметры включают общие настройки, такие как размер страницы, цвет фона и разрешение, а также настройки для конкретных устройств, включая сжатие изображений, защиту PDF и вставку шрифтов, которые позволяют полностью контролировать конечный результат.
Здесь вы найдете примеры кода на Python, демонстрирующие использование специфических параметров устройства. Использование общих параметров будет рассмотрено в главе “How-to Articles” (в процессе подготовки).
Чтобы узнать больше о процессе рендеринга, обратитесь к статье Rendering Device.
Класс
PdfRenderingOptions, наряду с общими опциями, поддерживает несколько специфических параметров, таких как jpeg_quality, document_info, encryption, form_field_behaviour и is_tagged_pdf.
| Property | Description |
|---|---|
| jpeg_quality | Specifies the quality of JPEG compression for images. The default value is 95. |
| document_info | 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. |
| form_field_behaviour | This property specifies the behavior of form fields in the output PDF document. |
| is_tagged_pdf | If is_tagged_pdf = true, a tag structure will be added to the PDF document during rendering. |
Свойство form_field_behaviour используется для указания поведения полей формы в PDF-документе. О том, что значит сплющить PDF-файл и как это сделать с помощью библиотеки Aspose.HTML for Python via .NET, читайте в разделе
Преобразование HTML в PDF с использованием свойства form_field_behaviour.
Следующий код на языке Python демонстрирует, как добавить шифрование в выходной файл PDF с помощью класса PdfRenderingOptions:
1# Render HTML to password-protected PDF in Python
2
3import os
4import aspose.html as ah
5import aspose.html.rendering as rn
6import aspose.html.rendering.pdf as rp
7import aspose.html.rendering.pdf.encryption as rpe
8
9# Prepare input and output paths
10data_dir = "data"
11output_dir = "output"
12os.makedirs(output_dir, exist_ok=True)
13
14document_path = os.path.join(data_dir, "document.html")
15save_path = os.path.join(output_dir, "convert-html-to-pdf-with-encryption.pdf")
16
17# Load the HTML document
18with ah.HTMLDocument(document_path) as document:
19 with rn.HtmlRenderer() as renderer:
20 # Configure password-protected PDF output
21 options = rp.PdfRenderingOptions()
22 options.encryption = rpe.PdfEncryptionInfo(
23 user_password="user_pwd",
24 owner_password="owner_pwd",
25 permissions=rpe.PdfPermissions.PRINT_DOCUMENT,
26 encryption_algorithm=rpe.PdfEncryptionAlgorithm.RC4_128
27 )
28
29 # Render HTML to PDF
30 with rp.PdfDevice(options, save_path) as device:
31 renderer.render(device, document)В примере выше показано, как создать новый экземпляр PdfRenderingOptions и задать параметры шифрования для выходного файла PDF. Для этого необходимо создать объект PdfEncryptionInfo, который определяет настройки шифрования для PDF-файла. Конструктор принимает четыре параметра:
user_password и owner_password, которые необходимы для открытия и работы с PDF-файлом;permissions – набор разрешенных прав для PDF-файла. В данном случае указано PdfPermissions.PRINT_DOCUMENT, что позволяет пользователю распечатать документ;encryption_algorithm – алгоритм шифрования, используемый для защиты PDF-файла. В данном случае используется PdfEncryptionAlgorithm.RC4_128, который представляет собой 128-битный алгоритм шифрования RC4.Класс 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. |
| use_antialiasing | This property defines the rendering quality of the image by controlling the use of antialiasing. Antialiasing is enabled by default. |
| text | Gets a TextOptions object which is used for configuration of text rendering. |
Рассмотрим, как использовать специализированный объект ImageRenderingOptions для установки формата TIFF и сжатия изображения:
1# Render HTML to TIFF in Python with custom settings
2
3import os
4import aspose.html as ah
5import aspose.html.rendering.image as ri
6
7# Prepare input and output paths
8data_dir = "data"
9output_dir = "output"
10os.makedirs(output_dir, exist_ok=True)
11
12document_path = os.path.join(data_dir, "html_file.html")
13save_path = os.path.join(output_dir, "document.tiff")
14
15# Load the HTML document
16with ah.HTMLDocument(document_path) as document:
17 # Configure TIFF output
18 options = ri.ImageRenderingOptions(ri.ImageFormat.TIFF)
19 options.compression = ri.Compression.NONE
20
21 # Render HTML to TIFF
22 with ri.ImageDevice(options, save_path) as device:
23 document.render_to(device)XpsRenderingOptions наследует все параметры от базового класса RenderingOptions. Вы можете настроить размер страницы, поля, цвет фона и другие общие параметры при генерации файлов XPS.
1# Render HTML to XPS in Python with custom page settings
2
3import os
4import aspose.html as ah
5import aspose.html.rendering.xps as rx
6import aspose.html.drawing as dr
7
8# Prepare input and output paths
9data_dir = "data"
10output_dir = "output"
11os.makedirs(output_dir, exist_ok=True)
12
13document_path = os.path.join(data_dir, "document.html")
14save_path = os.path.join(output_dir, "document-options.xps")
15
16# Load the HTML document
17with ah.HTMLDocument(document_path) as document:
18 # Configure XPS output
19 options = rx.XpsRenderingOptions()
20 options.page_setup.any_page = dr.Page(
21 dr.Size(dr.Length.from_inches(5.0), dr.Length.from_inches(2.0))
22 )
23
24 # Render HTML to XPS
25 with rx.XpsDevice(options, save_path) as device:
26 document.render_to(device)Класс
DocRenderingOptions поддерживает все общие параметры и позволяет настраивать свойства font_embedding_rule и document_format для выходного файла.
| Property | Description |
|---|---|
| font_embedding_rule | This property gets or sets the font embedding rule. Available values are Full and None. The default value is None. |
| document_format | This property gets or sets the file format of the output document. The default value is DOCX. |
В следующем примере показано, как настроить параметры рендеринга для выходного документа DOCX, задав размер страницы и правило встраивания шрифта:
1# Render HTML to DOCX in Python with custom settings
2
3import os
4import aspose.html as ah
5import aspose.html.rendering.doc as rd
6import aspose.html.drawing as dr
7
8# Prepare input and output paths
9data_dir = "data"
10output_dir = "output"
11os.makedirs(output_dir, exist_ok=True)
12
13document_path = os.path.join(data_dir, "nature.html")
14save_path = os.path.join(output_dir, "nature-options.docx")
15
16# Load the HTML document
17with ah.HTMLDocument(document_path) as document:
18 # Configure DOCX output
19 options = rd.DocRenderingOptions()
20 options.page_setup.any_page = dr.Page(
21 dr.Size(dr.Length.from_inches(8.0), dr.Length.from_inches(10.0))
22 )
23 options.font_embedding_rule = rd.FontEmbeddingRule.FULL
24
25 # Render HTML to DOCX
26 with rd.DocDevice(options, save_path) as device:
27 document.render_to(device)Aspose.HTML предлагает бесплатные онлайн Конверторы, которые позволяют преобразовать файлы HTML, XHTML, MHTML, EPUB, XML и Markdown в различные популярные форматы. Вы можете легко конвертировать HTML-документы в PDF, XPS, DOCX, JPG, PNG, GIF, TIFF и другие. Просто выберите файл, выберите формат для преобразования, и все готово.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.