Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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.
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.
| 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. |
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:
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)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:
user_password y owner_password, que son necesarias para abrir y trabajar con el archivo PDF;permissions – un conjunto de permisos permitidos para un archivo PDF. En este caso, se especifica PdfPermissions.PRINT_DOCUMENT, que permite al usuario imprimir el documento;encryption_algorithm – el algoritmo de cifrado utilizado para proteger el archivo PDF. En este caso, se utiliza PdfEncryptionAlgorithm.RC4_128, que es un algoritmo de cifrado RC4 de 128 bits.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.
| 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. |
Veamos cómo utilizar un objeto especializado ImageRenderingOptions para establecer el formato TIFF y la compresión de la imagen:
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 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.
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)La clase
DocRenderingOptions soporta todas las opciones generales y permite personalizar las propiedades font_embedding_rule y document_format para el fichero de salida.
| 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. |
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:
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 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.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.