Opciones de renderizado – Personalizar el renderizado HTML

Las opciones de renderizado proporcionan un control detallado sobre cómo el dispositivo de renderizado procesa el contenido. Cada dispositivo – PdfDevice, XpsDevice, DocDevice, y ImageDevice – tiene su propia clase de opciones: PdfRenderingOptions, XpsRenderingOptions, DocRenderingOptions, e ImageRenderingOptions. Con estas opciones, puede ajustar el tamaño de página, los márgenes y los colores, así como aplicar configuraciones específicas del dispositivo, como añadir una contraseña de seguridad a los archivos PDF. La personalización es crucial para lograr los resultados deseados, ya se trate de reducir el tamaño del archivo ajustando la calidad y la resolución de la imagen o de mejorar la legibilidad mediante un diseño de página y un formato de texto optimizados.

En este artículo, se exploran las opciones de renderizado en Aspose.HTML for Python via .NET, mostrando cómo personalizar la conversión de contenido HTML en formatos de salida como PDF, XPS, DOCX e imágenes. Estas opciones incluyen ajustes generales como el tamaño de página, el color de fondo y la resolución, así como ajustes específicos del dispositivo, como la compresión de imágenes, la seguridad de PDF y la incrustación de fuentes, que permiten un control total sobre el resultado final.

Aquí encontrarás ejemplos de código Python que demuestran el uso de parámetros específicos de dispositivo. El uso de opciones generales se tratará en el capítulo “Artículos prácticos” (en preparación).

Para saber más sobre el proceso de renderizado, lea el artículo Dispositivo de renderizado.

PdfRenderingOptions

La clase PdfRenderingOptions, junto con las opciones generales, soporta varios parámetros específicos, como jpeg_quality, document_info, encryption, form_field_behaviour, y is_tagged_pdf.

PropertyDescription
jpeg_qualitySpecifies the quality of JPEG compression for images. The default value is 95.
document_infoThis 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.
form_field_behaviourThis property specifies the behavior of form fields in the output PDF document.
is_tagged_pdfIf is_tagged_pdf = true, a tag structure will be added to the PDF document during rendering.

La propiedad form_field_behaviour se utiliza para especificar el comportamiento de los campos de formulario en un documento PDF. Para saber qué significa aplanar un archivo PDF y cómo hacerlo utilizando la biblioteca Aspose.HTML for Python via .NET, consulte la sección Conversión de HTML a PDF y PDF flattening.

El siguiente código de Python muestra cómo añadir encriptación a un archivo PDF utilizando la clase PdfRenderingOptions:

 1import os
 2import aspose.html as ah
 3import aspose.html.rendering as rn
 4import aspose.html.rendering.pdf as rp
 5import aspose.html.rendering.pdf.encryption as rpe
 6
 7# Setup input and output directories
 8data_dir = "data/"
 9output_dir = "output/"
10os.makedirs(output_dir, exist_ok=True)
11
12# Prepare path to the source HTML file
13document_path = os.path.join(data_dir, "document.html")
14
15# Initialize an HTML document from the file
16doc = ah.HTMLDocument(document_path)
17
18# Create an instance of the HTML Renderer
19renderer = rn.HtmlRenderer()
20
21# Prepare path to save the converted PDF
22save_path = os.path.join(output_dir, "convert-html-to-pdf-with-encryption.pdf")
23
24# Create PDF rendering options and set password protection
25options = rp.PdfRenderingOptions()
26options.encryption = rpe.PdfEncryptionInfo(
27    user_password="user_pwd",
28    owner_password="owner_pwd",
29    permissions=rpe.PdfPermissions.PRINT_DOCUMENT,
30    encryption_algorithm=rpe.PdfEncryptionAlgorithm.RC4_128
31)
32
33# Create the PDF device with options and output path
34device = rp.PdfDevice(options, save_path)
35
36# Render HTML to PDF
37renderer.render(device, doc)

El ejemplo anterior muestra cómo crear una nueva instancia de PdfRenderingOptions y establecer las opciones de cifrado para un archivo de salida PDF. Para ello, es necesario crear un objeto PdfEncryptionInfo, que define la configuración de cifrado para el archivo PDF. El constructor recibe cuatro parámetros:

ImageRenderingOptions

La clase ImageRenderingOptions soporta todas las opciones generales y permite configurar opciones específicas, como el antialiasing, la configuración del renderizado de texto, la selección del formato de imagen y la compresión de la imagen.

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.
use_antialiasingThis property defines the rendering quality of the image by controlling the use of antialiasing. Antialiasing is enabled by default.
textGets a TextOptions object which is used for configuration of text rendering.

Veamos cómo utilizar un objeto especializado ImageRenderingOptions para establecer el formato TIFF y la compresión de la imagen:

 1import os
 2import aspose.html as ah
 3import aspose.html.rendering.image as ri
 4
 5# Setup input and output directories
 6data_dir = "data/"
 7output_dir = "output/"
 8os.makedirs(output_dir, exist_ok=True)
 9
10# Prepare paths for input HTML and output TIFF file
11document_path = os.path.join(data_dir, "html_file.html")
12save_path = os.path.join(output_dir, "html_file.tiff")
13
14# Initialize an HTML document from the file
15doc = ah.HTMLDocument(document_path)
16
17# Create rendering options for image format (TIFF in this case)
18image_options = ri.ImageRenderingOptions(ri.ImageFormat.TIFF)
19image_options.compression = ri.Compression.NONE
20
21# Create an ImageDevice and specify options and output file
22device = ri.ImageDevice(image_options, save_path)
23
24# Render HTML to TIFF
25doc.render_to(device)

XpsRenderingOptions

XpsRenderingOptions heredan todas las opciones de la clase base RenderingOptions. Puede configurar el tamaño de página, los márgenes, el color de fondo y otras opciones comunes al generar archivos XPS.

 1import os
 2import aspose.html as ah
 3import aspose.html.rendering.xps as rx
 4import aspose.html.drawing as dr
 5
 6# Setup input and output directories
 7data_dir = "data/"
 8output_dir = "output/"
 9os.makedirs(output_dir, exist_ok=True)
10
11# Prepare a path to the source HTML file
12document_path = os.path.join(data_dir, "document.html")
13
14# Initialize the HTML document from the file
15doc = ah.HTMLDocument(document_path)
16
17# Create an instance of XPS Rendering Options
18options = rx.XpsRenderingOptions()
19
20# Set custom page size (5 x 2 inches)
21options.page_setup.any_page = dr.Page(dr.Size(dr.Length.from_inches(5.0), dr.Length.from_inches(2.0)))
22
23# Prepare a path to save the converted file
24save_path = os.path.join(output_dir, "document-options.xps")
25
26# Create an XpsDevice with the specified options and output file
27device = rx.XpsDevice(options, save_path)
28
29# Render HTML to XPS
30doc.render_to(device)

DocRenderingOptions

La clase DocRenderingOptions soporta todas las opciones generales y permite personalizar las propiedades font_embedding_rule y document_format para el fichero de salida.

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

El siguiente ejemplo muestra cómo personalizar las opciones de representación de un documento DOCX de salida estableciendo el tamaño de página y la regla de incrustación de fuentes:

 1import os
 2import aspose.html as ah
 3import aspose.html.rendering.doc as rd
 4import aspose.html.drawing as dr
 5
 6# Setup input and output directories
 7data_dir = "data/"
 8output_dir = "output/"
 9os.makedirs(output_dir, exist_ok=True)
10
11# Prepare a path to the source HTML file
12document_path = os.path.join(data_dir, "document.html")
13
14# Initialize the HTML document from the file
15doc = ah.HTMLDocument(document_path)
16
17# Create an instance of DocRenderingOptions and set a custom page size
18options = rd.DocRenderingOptions()
19options.page_setup.any_page = dr.Page(dr.Size(dr.Length.from_inches(8.0), dr.Length.from_inches(10.0)))
20options.font_embedding_rule = rd.FontEmbeddingRule.FULL
21
22# Prepare a path to save the converted file
23save_path = os.path.join(output_dir, "document-options.docx")
24
25# Create a DocDevice with the specified options and output file
26device = rd.DocDevice(options, save_path)
27
28# Render HTML to DOCX
29doc.render_to(device)

Aspose.HTML ofrece Convertidores en línea gratuitos que pueden convertir archivos HTML, XHTML, MHTML, EPUB, XML y Markdown a una serie de formatos populares. Puedes convertir fácilmente tus documentos basados en HTML a PDF, XPS, DOCX, JPG, PNG, GIF, TIFF y otros. Sólo tienes que seleccionar un archivo, elegir el formato a convertir y listo.

Texto “Aplicaciones web HTML”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.