COMPARACIóN DE PRODUCTOS

Tutorial de ActivePDF DocConverter y comparación con IronPDF

Chipego
Chipego Kalinda
23 de septiembre, 2021
Compartir:

El ActivePDF Toolkit es un componente de software utilizado para trabajar con archivos PDF (incluida la generación de archivos PDF desde diferentes fuentes) y establecer sus propiedades (como Encabezado, Pie de página, Margen o Marca de agua).

IronPDF es una librería PDF para C# que también ofrece estas funciones, con precios competitivos.

Aquí veremos las funciones, ejemplos de código y acciones paso a paso para utilizar ambos componentes de software en un proyecto .NET Visual Studio, para que pueda decidir por sí mismo qué es lo mejor para su aplicación.


Visión general

Acerca de la biblioteca IronPDF C

Iron Software es un proveedor de componentes líder en el mercado, que ofrece IronPDF para trabajar con archivos PDF. Una forma integral de generar fácilmente archivos PDF a partir de diferentes formatos y establecer todas las propiedades mediante programación. Es el preferido por los desarrolladores debido a la salida consistente, fiable y precisa de archivos PDF utilizando sólo unas pocas líneas de código.

IronPDF está diseñado para C#, .NET, VB, ASPX, ASP.NET, MVC y .NET Core. Es compatible con Visual Studio, NuGet, Linux, Azure, Docker, etc.

Acerca del kit de herramientas ActivePDF

ActivePDF es una empresa de software que ofrece muchos componentes para trabajar con archivos PDF. A diferencia del componente único IronPDF, ActivePDF ofrece diferentes soluciones para archivos PDF. Por ejemplo, para reducir el tamaño de los archivos PDF, puedes usar ActivePDF Compressor. Para crear PDFs a partir de fuentes HTML, usa ActivePDF WebGrabber.

En este artículo, utilizaremos ActivePDF WebGrabber para compararlo con IronPDF, echémosle un vistazo:

ActivePDF WebGrabber para crear archivos PDF

ActivePDF WebGrabber es un componente separado de ActivePDF utilizado específicamente para generar archivos PDF a partir de fuentes HTML como URL, archivo HTML o cadena HTML. También proporciona las funciones para establecer las propiedades de página como Encabezado, Pie de página, Margen, Marca de agua o Marca de libro para crear archivos PDF según nuestros requisitos.


Comparación

1. Tabla comparativa ActivePDF v IronPDF

Veamos la comparación entre ambos componentes.

IronPDFActivePDF
IronPDF converts HTML sources to PDF files.ActivePDF converts HTML sources to PDF files.
IronPDF supports .NET Core.ActivePDF does not support .NET Core.
IronPDF supports .NET 4.0 or higher.ActivePDF supports .NET 4.6.2 or higher.
IronPDF supports macOS.ActivePDF does not support macOS.
IronPDF can apply CSS to set WaterMark properties.ActivePDF does not support CSS to set WaterMark properties.
IronPDF can set Paper Orientation of PDF files.ActivePDF can set Paper Orientation of PDF files.
IronPDF provides the RenderDelay function to delay the PDF conversion.ActivePDF provides the TimeoutSpan function to delay the PDF conversion.
IronPDF provides predefined functions to set Header or Footer.ActivePDF requires setting Header and Footer by raw HTML and CSS.
IronPDF provides a predefined function to draw a horizontal line to separate content.ActivePDF does not provide a line to separate headers and footers.
To save the PDF file, we can set the directory and file name in one line.We have to set file directory and file name separately.
Need to write fewer lines of code with a simple programming structure.Need to write many lines of code.
License starts from $749.License starts from $1180.

Paso 1: Instalación

2. Cómo instalar IronPDF

Puede añadir la biblioteca IronPDF a su proyecto de dos formas distintas, sin que importe cuál adopte.

Gestor de paquetes NuGet

  • Abra el gestor de paquetes NuGet en su proyecto de Visual Studio.
  • Navega para IronPDF, luego instálalo.

    Alternativamente:

  • Ir a tools
  • Seleccione la consola del administrador de paquetes
  • Ejecute el siguiente comando:
Install-Package IronPdf

Descargar IronPDF.dll manualmente

También podemos descargar IronPDF.dll, luego agregar su referencia en el proyecto.

Si puedes acceder a IronPDF escribiendo using IronPdf; namespace, significa que IronPDF se ha importado correctamente en tu proyecto y está listo para su uso.


Cómo instalar WebGrabber

Descargue WebGrabber-install.exe y seleccione el archivo a descargar. Una vez que se haya descargado, haga doble clic en el archivo descargado. Luego solicite una clave de activación de ActivePDF para usar con la siguiente clave de evaluación de 15 días: 001-AEALX-LC6Z5-7YD95-S3D8J-3LR25.

Tras la instalación, vaya al siguiente directorio:

C:\Program Files\ActivePDF\WebGrabber\bin\

En este directorio, obtienes el archivo APWebGrabber.Net45.dll. Agrega su referencia en tu proyecto de Visual Studio.

Ahora, si puedes acceder a WebGrabber escribiendo using APWebGrabber; namespace, significa que ActivePDF WebGrabber se ha importado exitosamente en tu proyecto y puedes usarlo.

Documentación de ActivePDF está disponible para obtener más información sobre la instalación de ActivePDF WebGrabber.


Tutoriales

Uso de IronPDF y WebGrabber

Hemos visto la introducción de estos dos componentes y sus procesos de instalación, y ahora comenzaremos la comparación realizando diferentes tareas utilizando ambos. Esto nos permitirá entender la estructura de programación de ambos y decidir cuál es el mejor para nuestros proyectos. Para una mejor comprensión, ejecutaremos un caso de uso específico en cada tarea y proporcionaremos el código utilizado para implementarlo.


3. Convertir cadena HTML en archivo PDF

En la primera comparación, tomaremos un caso de uso en el que necesitamos crear un archivo PDF mediante una cadena HTML y guardarlo en la ubicación de destino. En primer lugar, empezamos a implementar este caso de uso mediante IronPDF:

3.1. Cadena HTML con IronPDF

/**
HTML String to PDF
anchor-html-string-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new ChromePdfRenderer();
    //HTML Source
    string html = "<h1>Hello World!</h1> <h2>Welcome to IronPDF</h2> ";
    //convert HTML string to PDF file
    using var PDF = converter.RenderHtmlAsPdf(html);
    //Save the file
    PDF.SaveAs("E:/sample.pdf");
}
/**
HTML String to PDF
anchor-html-string-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new ChromePdfRenderer();
    //HTML Source
    string html = "<h1>Hello World!</h1> <h2>Welcome to IronPDF</h2> ";
    //convert HTML string to PDF file
    using var PDF = converter.RenderHtmlAsPdf(html);
    //Save the file
    PDF.SaveAs("E:/sample.pdf");
}
'''
'''HTML String to PDF
'''anchor-html-string-with-ironpdf
'''*
Imports IronPdf
Shared Sub Main(ByVal args() As String)
	'create rendering converter
	Dim converter = New ChromePdfRenderer()
	'HTML Source
	Dim html As String = "<h1>Hello World!</h1> <h2>Welcome to IronPDF</h2> "
	'convert HTML string to PDF file
	Dim PDF = converter.RenderHtmlAsPdf(html)
	'Save the file
	PDF.SaveAs("E:/sample.pdf")
End Sub
$vbLabelText   $csharpLabel

Salida:

El código anterior creará un archivo PDF sample.pdf en Disco local E: y su captura de pantalla es:

Iron1 related to 3.1. Cadena HTML con IronPDF

3.2. Cadena HTML con ActivePDF

using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //HTML Source
    string html = "<h1>Hello World!</h1> <h2>Welcome to ActivePDF WebGrabber</h2>";
    //assign source html to WebGrabber
    wg.CreateFromHTMLText = html;
    //specify file directory
    wg.OutputDirectory = "E:/";
    // file name
    wg.NewDocumentName = "sample.pdf";
    //convert source HTML to PDF file
    wg.ConvertToPDF();
}
using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //HTML Source
    string html = "<h1>Hello World!</h1> <h2>Welcome to ActivePDF WebGrabber</h2>";
    //assign source html to WebGrabber
    wg.CreateFromHTMLText = html;
    //specify file directory
    wg.OutputDirectory = "E:/";
    // file name
    wg.NewDocumentName = "sample.pdf";
    //convert source HTML to PDF file
    wg.ConvertToPDF();
}
Imports APWebGrabber
Shared Sub Main(ByVal args() As String)
	'Instantiate Object
	Dim wg As New WebGrabber()
	'HTML Source
	Dim html As String = "<h1>Hello World!</h1> <h2>Welcome to ActivePDF WebGrabber</h2>"
	'assign source html to WebGrabber
	wg.CreateFromHTMLText = html
	'specify file directory
	wg.OutputDirectory = "E:/"
	' file name
	wg.NewDocumentName = "sample.pdf"
	'convert source HTML to PDF file
	wg.ConvertToPDF()
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es el archivo sample.pdf recién generado a partir de este código:

Active1 related to 3.2. Cadena HTML con ActivePDF

3.3. Diferencia entre IronPDF y ActivePDF

  • Menos líneas de código con IronPDF
  • El archivo generado por IronPDF es más legible, gracias a los márgenes por defecto

4. Convertir archivo HTML a PDF

En esta comparación, tomamos el caso de uso en el que necesitamos generar un archivo PDF a partir de un archivo HTML llamado myHtmlFile.html que existe en el directorio E:/, y tiene el siguiente código HTML y CSS:

<html>
  <style>
        li{
            font-size:x-large;
            color: magenta;
            font-style: italic;
            }
  </style>
<body>
    <h1>I am Heading</h1>
    <h2>Items List:</h2>
    <ul>
        <li>Item1</li>
        <li>Item2</li>
        <li>Item3</li>
        <li>Item4</li>
    </ul>
</body>
</html>
<html>
  <style>
        li{
            font-size:x-large;
            color: magenta;
            font-style: italic;
            }
  </style>
<body>
    <h1>I am Heading</h1>
    <h2>Items List:</h2>
    <ul>
        <li>Item1</li>
        <li>Item2</li>
        <li>Item3</li>
        <li>Item4</li>
    </ul>
</body>
</html>
HTML

Ahora, convertiremos el archivo myHtmlFile.html a un archivo PDF utilizando ambos componentes. Empecemos por IronPDF.

4.1. Archivo HTML con IronPDF

/**
HTML File to PDF
anchor-html-file-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new IronPdf.ChromePdfRenderer();
    //render html file to pdf
    using var PDF = converter.RenderHTMLFileAsPdf("E:/myHtmlFile.html");
    //save to target location
    PDF.SaveAs("E:/Sample.pdf");
}
/**
HTML File to PDF
anchor-html-file-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new IronPdf.ChromePdfRenderer();
    //render html file to pdf
    using var PDF = converter.RenderHTMLFileAsPdf("E:/myHtmlFile.html");
    //save to target location
    PDF.SaveAs("E:/Sample.pdf");
}
'''
'''HTML File to PDF
'''anchor-html-file-with-ironpdf
'''*
Imports IronPdf
Shared Sub Main(ByVal args() As String)
	'create rendering converter
	Dim converter = New IronPdf.ChromePdfRenderer()
	'render html file to pdf
	Dim PDF = converter.RenderHTMLFileAsPdf("E:/myHtmlFile.html")
	'save to target location
	PDF.SaveAs("E:/Sample.pdf")
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado utilizando el código anterior:

Iron2 related to 4.1. Archivo HTML con IronPDF

Podemos ver que la página HTML myHtmlFile.html se convirtió con éxito en el archivo PDF Sample.pdf, y los estilos CSS también se aplicaron.

Lea la documentación de IronPDF para obtener más información sobre cómo podemos usar IronPDF en nuestro proyecto .NET.

Realicemos la misma tarea utilizando ActivePDF WebGrabber.

4.2. Archivo HTML con ActivePDF

using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //specify file path to be converted
    wg.URL = "E:/myHtmlFile.html";
    //specify the directory for newly generated file
    wg.OutputDirectory = "E:/";
    //newly generated file name
    wg.NewDocumentName = "Sample.pdf";
    //convert HTML file to PDF
    wg.ConvertToPDF();
}
using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //specify file path to be converted
    wg.URL = "E:/myHtmlFile.html";
    //specify the directory for newly generated file
    wg.OutputDirectory = "E:/";
    //newly generated file name
    wg.NewDocumentName = "Sample.pdf";
    //convert HTML file to PDF
    wg.ConvertToPDF();
}
Imports APWebGrabber
Shared Sub Main(ByVal args() As String)
	'Instantiate Object
	Dim wg As New WebGrabber()
	'specify file path to be converted
	wg.URL = "E:/myHtmlFile.html"
	'specify the directory for newly generated file
	wg.OutputDirectory = "E:/"
	'newly generated file name
	wg.NewDocumentName = "Sample.pdf"
	'convert HTML file to PDF
	wg.ConvertToPDF()
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado, utilizando el código anterior:

Active2 related to 4.2. Archivo HTML con ActivePDF

4.3. Diferencia entre IronPDF y ActivePDF

  • Sólo 3 líneas de código con IronPDF
  • El archivo IronPDF es ligeramente más limpio / atractivo

5. Convertir URL en archivo PDF

Supongamos que tenemos una URL https://yandex.com/ y queremos generar un archivo PDF de su página web. Para ello, ambos componentes proporcionan una función. En primer lugar, veremos cómo puede hacerlo IronPDF.

5.1. URL con IronPDF

/**
URL to PDF
anchor-url-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new ChromePdfRenderer();
    //Specify URL
    using var PDF = converter.RenderUrlAsPdf("https://yandex.com/");
    //Save the file
    PDF.SaveAs("E:/Sample.pdf");
}
/**
URL to PDF
anchor-url-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new ChromePdfRenderer();
    //Specify URL
    using var PDF = converter.RenderUrlAsPdf("https://yandex.com/");
    //Save the file
    PDF.SaveAs("E:/Sample.pdf");
}
'''
'''URL to PDF
'''anchor-url-with-ironpdf
'''*
Imports IronPdf
Shared Sub Main(ByVal args() As String)
	'create rendering converter
	Dim converter = New ChromePdfRenderer()
	'Specify URL
	Dim PDF = converter.RenderUrlAsPdf("https://yandex.com/")
	'Save the file
	PDF.SaveAs("E:/Sample.pdf")
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado por el código anterior

Iron3 related to 5.1. URL con IronPDF

Puede visitar la página web de la muestra de URL para comparar y ver qué tan exactamente coincide el archivo de IronPDF.

Ahora, haremos la misma tarea utilizando ActivePDF WebGrabber.

5.2. URL con ActivePDF

using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //specify URL 
    wg.URL = "https://yandex.com/";
    //specify the directory for newly generated file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert specified URL webpage to PDF
    wg.ConvertToPDF();
}
using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //specify URL 
    wg.URL = "https://yandex.com/";
    //specify the directory for newly generated file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert specified URL webpage to PDF
    wg.ConvertToPDF();
}
Imports APWebGrabber
Shared Sub Main(ByVal args() As String)
	'Instantiate Object
	Dim wg As New WebGrabber()
	'specify URL 
	wg.URL = "https://yandex.com/"
	'specify the directory for newly generated file
	wg.OutputDirectory = "E:/"
	'specify file name
	wg.NewDocumentName = "Sample.pdf"
	'convert specified URL webpage to PDF
	wg.ConvertToPDF()
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado por el código anterior:

Active3 related to 5.2. URL con ActivePDF

5.3. Diferencia entre IronPDF y ActivePDF

  • IronPDF tiene una estructura más sencilla para generar archivos PDF
  • Sólo tres líneas de código
  • IronPDF se acerca más al sitio

6. Crear una marca de agua en PDF

En esta comparación, crearemos un archivo PDF utilizando una cadena HTML, y luego añadiremos una Marca de Agua en el centro de la página. Empecemos por IronPDF.

6.1. Marca de agua con IronPDF

IronPDF proporciona la siguiente función para añadir WaterMark:

WatermarkPage(Cadena HTML WaterMark, PageIndexToWaterMark, WaterMarkLocation, Opacity, Rotation, Hyperlink)

Podemos usar el WaterMarkLocation para establecer la marca de agua en las siguientes posiciones:

  • EsquinaSuperiorIzquierda

  • Centro Superior

  • Arriba a la derecha

  • MiddleLeft

  • CentroMedio

  • Centrado a la derecha

  • InferiorIzquierda

  • FondoCentro

  • InferiorDerecha

    Veamos cómo utilizar las funciones anteriores para establecer la marca de agua:

/**
Watermark PDF
anchor-watermark-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new ChromePdfRenderer();
    //source html string
    string html = "<h1 style='text-align:center'>WaterMark Example</h1>";
    //add above string as PDF file content
    using var PDF = converter.RenderHtmlAsPdf(html);
    //HTML string for WaterMark
    string WMStr = "<h1 style='color:red'>WaterMark</h1>";
    //add WaterMark
    PDF.WatermarkPage(WMStr, 0, PdfDocument.WaterMarkLocation.MiddleCenter, 100, -45, "");
    //save the document
    PDF.SaveAs("E:/Sample.pdf");
}
/**
Watermark PDF
anchor-watermark-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create rendering converter
    var converter = new ChromePdfRenderer();
    //source html string
    string html = "<h1 style='text-align:center'>WaterMark Example</h1>";
    //add above string as PDF file content
    using var PDF = converter.RenderHtmlAsPdf(html);
    //HTML string for WaterMark
    string WMStr = "<h1 style='color:red'>WaterMark</h1>";
    //add WaterMark
    PDF.WatermarkPage(WMStr, 0, PdfDocument.WaterMarkLocation.MiddleCenter, 100, -45, "");
    //save the document
    PDF.SaveAs("E:/Sample.pdf");
}
'''
'''Watermark PDF
'''anchor-watermark-with-ironpdf
'''*
Imports IronPdf
Shared Sub Main(ByVal args() As String)
	'create rendering converter
	Dim converter = New ChromePdfRenderer()
	'source html string
	Dim html As String = "<h1 style='text-align:center'>WaterMark Example</h1>"
	'add above string as PDF file content
	Dim PDF = converter.RenderHtmlAsPdf(html)
	'HTML string for WaterMark
	Dim WMStr As String = "<h1 style='color:red'>WaterMark</h1>"
	'add WaterMark
	PDF.WatermarkPage(WMStr, 0, PdfDocument.WaterMarkLocation.MiddleCenter, 100, -45, "")
	'save the document
	PDF.SaveAs("E:/Sample.pdf")
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado por el código anterior:

Iron4 related to 6.1. Marca de agua con IronPDF

Podemos añadir cualquier tipo de WaterMark y establecer sus propiedades mediante CSS. Ahora, haremos la misma tarea utilizando ActivePDF WebGrabber.

6.2. Marca de agua con ActivePDF

ActivePDF WebGrabber no proporciona una función específica para WaterMark, a diferencia de IronPDF. Pero podemos usar la función AddStampText() como una solución alternativa para este propósito:

AddStampText(float x, float y, string stampText);

  • float x para establecer la coordenada x para el origen del nuevo TextStamp.
  • float y para establecer la coordenada y para el origen del nuevo TextStamp.
  • stampText es el texto real del TextStamp.

    Nota: ActivePDF WebGrabber no admite el estilo CSS para TextStamp. Debemos configurarlo mediante otras funciones proporcionadas de la siguiente manera:

using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //HTML source for Page content
    string html = "<h1 style='text-align:center'>WaterMark Example</h1>";
    //assign page content source
    wg.CreateFromHTMLText = html;
    //add text stamp as WaterMark
    wg.AddStampText(270.0f, 350.0f, "WaterMark");
    //specify WaterMark's font size
    wg.StampFontSize = 20;
    //specify WaterMark's font family
    wg.StampFont = "Times New Roman";
    //specify WaterMark's opacity
    wg.StampFontTransparency = 1f;
    //specify WaterMark's rotation
    wg.StampRotation = 45.0f;
    //specify WaterMark's color
    wg.StampColorNET = new ADK.PDF.Color() { Red = 255, Green = 0, Blue = 0, Gray = 0 };
    //specify directory for newly created file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert above sources to PDF file
    wg.ConvertToPDF();
}
using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //HTML source for Page content
    string html = "<h1 style='text-align:center'>WaterMark Example</h1>";
    //assign page content source
    wg.CreateFromHTMLText = html;
    //add text stamp as WaterMark
    wg.AddStampText(270.0f, 350.0f, "WaterMark");
    //specify WaterMark's font size
    wg.StampFontSize = 20;
    //specify WaterMark's font family
    wg.StampFont = "Times New Roman";
    //specify WaterMark's opacity
    wg.StampFontTransparency = 1f;
    //specify WaterMark's rotation
    wg.StampRotation = 45.0f;
    //specify WaterMark's color
    wg.StampColorNET = new ADK.PDF.Color() { Red = 255, Green = 0, Blue = 0, Gray = 0 };
    //specify directory for newly created file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert above sources to PDF file
    wg.ConvertToPDF();
}
Imports APWebGrabber
Shared Sub Main(ByVal args() As String)
	'Instantiate Object
	Dim wg As New WebGrabber()
	'HTML source for Page content
	Dim html As String = "<h1 style='text-align:center'>WaterMark Example</h1>"
	'assign page content source
	wg.CreateFromHTMLText = html
	'add text stamp as WaterMark
	wg.AddStampText(270.0F, 350.0F, "WaterMark")
	'specify WaterMark's font size
	wg.StampFontSize = 20
	'specify WaterMark's font family
	wg.StampFont = "Times New Roman"
	'specify WaterMark's opacity
	wg.StampFontTransparency = 1F
	'specify WaterMark's rotation
	wg.StampRotation = 45.0F
	'specify WaterMark's color
	wg.StampColorNET = New ADK.PDF.Color() With {
		.Red = 255,
		.Green = 0,
		.Blue = 0,
		.Gray = 0
	}
	'specify directory for newly created file
	wg.OutputDirectory = "E:/"
	'specify file name
	wg.NewDocumentName = "Sample.pdf"
	'convert above sources to PDF file
	wg.ConvertToPDF()
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado.

Active4 related to 6.2. Marca de agua con ActivePDF

6.3. Diferencia entre IronPDF y ActivePDF

  • IronPDF hace que sea muy sencillo añadir una marca de agua
  • IronPDF ofrece funciones directas para establecer las propiedades de la marca de agua
  • ActivePDF WebGrabber tiene una estructura de programación compleja con muchas líneas de código en las que trabajar

7. Establecer márgenes en página PDF

Supongamos que tenemos una simple página web llamada myHtmlFile.html en nuestro Disco Local E, que tiene un ancho del 100% y un borde de color negro. Generaremos un archivo PDF a partir de él y estableceremos el Margen de página. Empecemos por IronPDF.

7.1. Márgenes con IronPDF

Para establecer los márgenes, IronPDF proporciona la clase ChromePdfRenderOptions, que tiene las siguientes propiedades:

  • MarginLeft para establecer el margen desde el lado izquierdo de la página.
  • MarginRight para establecer el margen desde el lado derecho de la página.
  • MarginTop para establecer el margen desde la parte superior de la página.
  • MarginBottom para establecer un margen desde la parte inferior de la página.

    Nota: De forma predeterminada, IronPDF establece un margen de 20mm desde la izquierda, arriba, derecha y abajo para que la página sea más legible. Podemos establecerlo en 0mm si no lo necesitamos.

/**
Set Margins
anchor-margins-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create html to PDF converter
    var converter = new ChromePdfRenderer();
    //specify left Margin
    converter.RenderingOptions.MarginLeft = 50;
    //specify top Margin
    converter.RenderingOptions.MarginTop = 40;
    //render html file to PDF
    using var PDF = converter.RenderHTMLFileAsPdf("E:/myHtmlFile.html");
    //save to the target location
    PDF.SaveAs("E:/Sample.pdf");
}
/**
Set Margins
anchor-margins-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create html to PDF converter
    var converter = new ChromePdfRenderer();
    //specify left Margin
    converter.RenderingOptions.MarginLeft = 50;
    //specify top Margin
    converter.RenderingOptions.MarginTop = 40;
    //render html file to PDF
    using var PDF = converter.RenderHTMLFileAsPdf("E:/myHtmlFile.html");
    //save to the target location
    PDF.SaveAs("E:/Sample.pdf");
}
'''
'''Set Margins
'''anchor-margins-with-ironpdf
'''*
Imports IronPdf
Shared Sub Main(ByVal args() As String)
	'create html to PDF converter
	Dim converter = New ChromePdfRenderer()
	'specify left Margin
	converter.RenderingOptions.MarginLeft = 50
	'specify top Margin
	converter.RenderingOptions.MarginTop = 40
	'render html file to PDF
	Dim PDF = converter.RenderHTMLFileAsPdf("E:/myHtmlFile.html")
	'save to the target location
	PDF.SaveAs("E:/Sample.pdf")
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado por el código anterior:

Iron5 related to 7.1. Márgenes con IronPDF

Se puede ver que la página PDF tiene 50mm desde el lado izquierdo, 40 desde la parte superior, y el margen izquierdo es de 20mm que es por defecto. Podemos ver lo simple que es establecer el margen de cualquier lado utilizando la clase ChromePdfRenderOptions de IronPDF.

Lea más sobre Configuración de Generación de PDF para más detalles: cómo trabajar con márgenes y otras propiedades del archivo PDF.

Ahora, estableceremos el Margen de la página utilizando ActivePDF WebGrabber.

7.2. Márgenes con ActivePDF

Para establecer los márgenes de la página, ActivePDF WebGrabber proporciona la función SetMargins(), y podemos usarla de la siguiente manera:

SetMargins(Margen Superior, Margen Inferior, Margen Izquierdo, Margen Derecho)

Utilizaremos esta función para establecer el margen de página:

using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber()
    //specify source HTML file path
    wg.URL = "E:/myHtmlFile.html";
    //Margins
    wg.SetMargins(1, 0, 1.5f, 0);
    //specify directory for newly created file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert HTML file to PDF
    wg.ConvertToPDF();
}
using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber()
    //specify source HTML file path
    wg.URL = "E:/myHtmlFile.html";
    //Margins
    wg.SetMargins(1, 0, 1.5f, 0);
    //specify directory for newly created file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert HTML file to PDF
    wg.ConvertToPDF();
}
Imports APWebGrabber
Shared Sub Main(ByVal args() As String)
	'Instantiate Object
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: WebGrabber wg = new WebGrabber() wg.URL = "E:/myHtmlFile.html";
	New WebGrabber() wg.URL = "E:/myHtmlFile.html"
	Dim wg As New WebGrabber() wg.URL
	'Margins
	wg.SetMargins(1, 0, 1.5F, 0)
	'specify directory for newly created file
	wg.OutputDirectory = "E:/"
	'specify file name
	wg.NewDocumentName = "Sample.pdf"
	'convert HTML file to PDF
	wg.ConvertToPDF()
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado por el código anterior:

Active5 related to 7.2. Márgenes con ActivePDF

Podemos ver que la página PDF tiene un Margen de 1.5f del lado izquierdo y 1f desde la parte superior. Utilizando ambos componentes, podemos establecer fácilmente los márgenes de página según nuestras necesidades.

Lea más sobre cómo establecer márgenes con ActivePDF.


8. Establecer encabezado y pie de página para PDF

En esta comparación, veremos cómo establecer el Encabezado y el Pie de página de un archivo PDF. Utilizaremos las funciones y técnicas proporcionadas por ambos componentes, a través de las cuales podemos imprimir encabezados y pies de página personalizados en páginas PDF mediante programación.

8.1. Encabezados y pies de página con IronPDF

IronPDF proporciona las siguientes propiedades, que pueden utilizarse para establecer tanto Encabezados como Pies de página:

  • LeftText : establece el texto del encabezado o pie de página en el lado izquierdo.
  • CenterText : imprime el texto del Encabezado o el Pie de página en el centro.
  • RightText : establece el texto del encabezado o pie de página en el lado izquierdo.
  • FontFamily : establece la familia de fuentes del texto del Encabezado o Pie de página.
  • FontSize : establece el tamaño de fuente del texto de encabezado o pie de página.
  • Espaciado : establece el espacio entre el contenido de la página y el encabezado o pie de página.
  • DrawDividerLine: dibuja una línea horizontal que separa el contenido de la página del Encabezado o Pie de página.

    Podemos utilizar las siguientes funciones predefinidas de IronPDF en llaves {} para el encabezado o pie de página:

  • {page} imprime el número de la página actual.
  • {total-pages} se utiliza para imprimir el número total de páginas de un PDF.
  • {url} se utiliza para imprimir la URL del PDF renderizado.
  • {date} se utiliza para imprimir la fecha de hoy.
  • {time} imprime la hora actual.
  • {html-title} se utiliza para imprimir el título del archivo HTML renderizado.
  • {pdf-title} establece el título del documento.

    Veamos el siguiente ejemplo, en el que estableceremos el Encabezado y el Pie de Página utilizando las funciones anteriores:

/**
Set Header Footers
anchor-headers-and-footers-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create html to PDF converter
    var converter = new IronPdf.ChromePdfRenderer();
    //Page Content source
    string html = "<h1 style='text-align:center;'>Page Content</h2>";
    //Assign source to converter
    using var PDF = converter.RenderHtmlAsPdf(html);
    //Add Header settings
    converter.RenderingOptions.TextHeader = new TextHeaderFooter()
    {
        LeftText = "Header Text",
        RightText = "{date} {time}",
        DrawDividerLine=true,
        FontSize=13
    };
    //Add Footer settings
    converter.RenderingOptions.TextFooter = new TextHeaderFooter()
    {
        RightText = "Page {page} of {total-pages}",
        FontSize = 12
    };
    //save to target location
    PDF.SaveAs("E:/Sample.pdf");
}
/**
Set Header Footers
anchor-headers-and-footers-with-ironpdf
**/
using IronPdf;
static void Main(string [] args)
{
    //create html to PDF converter
    var converter = new IronPdf.ChromePdfRenderer();
    //Page Content source
    string html = "<h1 style='text-align:center;'>Page Content</h2>";
    //Assign source to converter
    using var PDF = converter.RenderHtmlAsPdf(html);
    //Add Header settings
    converter.RenderingOptions.TextHeader = new TextHeaderFooter()
    {
        LeftText = "Header Text",
        RightText = "{date} {time}",
        DrawDividerLine=true,
        FontSize=13
    };
    //Add Footer settings
    converter.RenderingOptions.TextFooter = new TextHeaderFooter()
    {
        RightText = "Page {page} of {total-pages}",
        FontSize = 12
    };
    //save to target location
    PDF.SaveAs("E:/Sample.pdf");
}
'''
'''Set Header Footers
'''anchor-headers-and-footers-with-ironpdf
'''*
Imports IronPdf
Shared Sub Main(ByVal args() As String)
	'create html to PDF converter
	Dim converter = New IronPdf.ChromePdfRenderer()
	'Page Content source
	Dim html As String = "<h1 style='text-align:center;'>Page Content</h2>"
	'Assign source to converter
	Dim PDF = converter.RenderHtmlAsPdf(html)
	'Add Header settings
	converter.RenderingOptions.TextHeader = New TextHeaderFooter() With {
		.LeftText = "Header Text",
		.RightText = "{date} {time}",
		.DrawDividerLine=True,
		.FontSize=13
	}
	'Add Footer settings
	converter.RenderingOptions.TextFooter = New TextHeaderFooter() With {
		.RightText = "Page {page} of {total-pages}",
		.FontSize = 12
	}
	'save to target location
	PDF.SaveAs("E:/Sample.pdf")
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado por el código anterior:

Iron6 related to 8.1. Encabezados y pies de página con IronPDF

Podemos ver que

  • El Header Text se imprime en el lado izquierdo del encabezado.
  • DateTime se imprime en el lado derecho del encabezado.
  • Se traza una línea horizontal que separa la cabecera del contenido de la página.
  • Página CurrentPage de TotalPages en el lado derecho del pie de página.

    Lea más sobre cómo establecer propiedades de HTML a PDF utilizando IronPDF.

    Utilicemos ahora ActivePDF WebGrabber para establecer encabezados y pies de página:

8.2. Encabezados y pies de página con ActivePDF

ActivePDF WebGrabber proporciona las propiedades HeaderHTML y FooterHTML para establecer el encabezado y el pie de página respectivamente. El HTML en bruto se pasa a estas propiedades como Cabecera o Pie de Página. A diferencia de IronPDF, ActivePDF WebGrabber no proporciona funciones predefinidas para establecer la alineación del Encabezado y Pie de Página, por lo que tenemos que establecerla utilizando propiedades HTML y CSS como se indica a continuación:

using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //Page content source
    string html = @"<h1 style='text-align:center;'>Page Content</h2>";
    //assign above source to WebGrabber
    wg.CreateFromHTMLText = html;
    //specify Footer height
    wg.FooterHeight = 0.5f;
    //Add Footer setting
    wg.FooterHTML = "<div style='text-align: right;'>%cp% of %tp%</div>";
    //create object for datetime
    DateTime now = DateTime.Now;
    //specify header height
    wg.HeaderHeight = 0.5f;
    //Add Header setting
    wg.HeaderHTML = "<div style='float: left;'>Header Text</div>";
    //append Header settings
    wg.HeaderHTML = $"<div style='float: right;'>{DateTime.Now.ToShortDateString()} {DateTime.Now.ToShortTimeString()}</div>";
    //specify directory for newly created file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert above sources to PDF file
    wg.ConvertToPDF();
}
using APWebGrabber;
static void Main(string [] args)
{
    //Instantiate Object
    WebGrabber wg = new WebGrabber();
    //Page content source
    string html = @"<h1 style='text-align:center;'>Page Content</h2>";
    //assign above source to WebGrabber
    wg.CreateFromHTMLText = html;
    //specify Footer height
    wg.FooterHeight = 0.5f;
    //Add Footer setting
    wg.FooterHTML = "<div style='text-align: right;'>%cp% of %tp%</div>";
    //create object for datetime
    DateTime now = DateTime.Now;
    //specify header height
    wg.HeaderHeight = 0.5f;
    //Add Header setting
    wg.HeaderHTML = "<div style='float: left;'>Header Text</div>";
    //append Header settings
    wg.HeaderHTML = $"<div style='float: right;'>{DateTime.Now.ToShortDateString()} {DateTime.Now.ToShortTimeString()}</div>";
    //specify directory for newly created file
    wg.OutputDirectory = "E:/";
    //specify file name
    wg.NewDocumentName = "Sample.pdf";
    //convert above sources to PDF file
    wg.ConvertToPDF();
}
Imports APWebGrabber
Shared Sub Main(ByVal args() As String)
	'Instantiate Object
	Dim wg As New WebGrabber()
	'Page content source
	Dim html As String = "<h1 style='text-align:center;'>Page Content</h2>"
	'assign above source to WebGrabber
	wg.CreateFromHTMLText = html
	'specify Footer height
	wg.FooterHeight = 0.5F
	'Add Footer setting
	wg.FooterHTML = "<div style='text-align: right;'>%cp% of %tp%</div>"
	'create object for datetime
	Dim now As DateTime = DateTime.Now
	'specify header height
	wg.HeaderHeight = 0.5F
	'Add Header setting
	wg.HeaderHTML = "<div style='float: left;'>Header Text</div>"
	'append Header settings
	wg.HeaderHTML = $"<div style='float: right;'>{DateTime.Now.ToShortDateString()} {DateTime.Now.ToShortTimeString()}</div>"
	'specify directory for newly created file
	wg.OutputDirectory = "E:/"
	'specify file name
	wg.NewDocumentName = "Sample.pdf"
	'convert above sources to PDF file
	wg.ConvertToPDF()
End Sub
$vbLabelText   $csharpLabel

La siguiente captura de pantalla es del archivo Sample.pdf recién generado a partir del código anterior:

Active6 related to 8.2. Encabezados y pies de página con ActivePDF

Lea más sobre cómo configurar encabezados y pies de página con ActivePDF WebGrabber.

8.3. Diferencia entre IronPDF y ActivePDF

  • ActivePDF WebGrabber no tiene una función predefinida para dibujar una línea horizontal que separe el encabezado del contenido de la página.
  • ActivePDF requiere el uso de la función DateTime del framework .NET
  • IronPDF ofrece una configuración sencilla de las propiedades de encabezado y pie de página

9. Lista de componentes de ActivePDF

NameDetail
ActivePDF DocConverterIt is used to convert popular file types to and from PDF format.
ActivePDF WebGrabberIt grabs the HTML from many sources and converts it to PDF files.
ActivePDF DocSpaceIt provides Batch Process Automation, and a user interface for display, generate, converting, manipulating, and interacting with PDF and other file formats.
ActivePDF ToolkitIt is used to create, modify, view, extract, manipulate, and automate the document content to and from PDF files.
ActivePDF PortalIt enables the users to view and modify PDF documents from any source in a standard web browser.
ActivePDF CADConverterIt is used to convert CAD files into PDF.
ActivePDF XtractorIt is used to extract and find the text and images from PDF files.
ActivePDF SpoolerIt allows the developer to print the PDF file page on paper.
ActivePDF RedactorIt is used to hide sensitive information from the viewer.
ActivePDF ServerIt provides the printing solution for different purposes.

10. Licencias

ActivePDF no proporciona ninguna información sobre sus paquetes en su sitio web de ActivePDF. Para obtener información sobre las licencias, debe contactar a su representante de ventas. Sin embargo, debe saber exactamente qué tipo de licencia de producción está buscando. No facilitan una lista de precios, y aunque los precios empiezan en 1.180 dólares por una licencia anual, pueden ser más altos dependiendo del ámbito de uso y hay que detallarlos para obtener un presupuesto.

IronPDF ofrece precios transparentes con licencias desde $749, con muchas opciones personalizables. Póngase en contacto con el equipo si tiene alguna duda.


Acceso rápido a tutoriales

Explorar la referencia API de IronPDF

Explore la Referencia de la API para la Biblioteca IronPDF C#, incluyendo detalles de todas las características, clases, campos de métodos, espacios de nombres y enums de IronPDF.

Ver la referencia de la API
Documentation related to Acceso rápido a tutoriales
Chipego
Ingeniero de software
Chipego tiene una habilidad natural para escuchar que le ayuda a comprender los problemas de los clientes y a ofrecer soluciones inteligentes. Se unió al equipo de Iron Software en 2023, después de estudiar una licenciatura en Tecnología de la Información. IronPDF e IronOCR son los dos productos en los que Chipego se ha centrado, pero su conocimiento de todos los productos crece día a día, a medida que encuentra nuevas formas de ayudar a los clientes. Disfruta de lo colaborativa que es la vida en Iron Software, con miembros del equipo de toda la empresa que aportan su variada experiencia para contribuir a soluciones eficaces e innovadoras. Cuando Chipego está lejos de su escritorio, a menudo se le puede encontrar disfrutando de un buen libro o jugando al fútbol.
< ANTERIOR
Tutorial y comparación de Aspose PDF Converter
SIGUIENTE >
SpirePDF C# HTML to PDF Tutorial & Comparación de bibliotecas