Saltar al pie de página
GUíAS DE MIGRACIóN

Cómo migrar de Aspose.PDF a IronPDF en C#

Migrar de Aspose.PDF a IronPDF: Guía completa de migración de C

Aspose.PDF para .NET es una biblioteca PDF empresarial bien establecida, conocida por sus completas funciones de manipulación de documentos. Sin embargo, su modelo de precios premium (más de 1.199 dólares anuales por desarrollador), los problemas de rendimiento documentados (hasta 30 veces más lento en algunos casos) y el motor de renderizado HTML anticuado Flying Saucer crean razones de peso para que los equipos de desarrollo busquen alternativas. Esta completa guía proporciona una ruta de migración paso a paso de Aspose.PDF a IronPDF, una biblioteca PDF nativa de .NET con un moderno renderizado basado en Chromium, compatibilidad superior con CSS3 y licencia perpetua única.

¿Por qué migrar de Aspose.PDF?

Aunque Aspose.PDF ofrece funcionalidad de nivel empresarial, varios factores llevan a los equipos de desarrollo a buscar alternativas modernas para sus necesidades de generación de PDF.

Comparación de costes

Aspose.PDF utiliza un modelo de licencia empresarial tradicional con renovaciones anuales que se acumulan significativamente con el tiempo:

AspectoAspose.PDFIronPDF
Precio Inicial1.199 $/desarrollador/año749 $ por única vez (Lite)
Modelo de licenciaSuscripción anual + renovaciónLicencia perpetua
Licencia OEM$5,997+ adicionalIncluido en niveles superiores
SoporteNiveles de coste adicionalesSe incluye
Coste total de 3 años$3,597+ por desarrollador749 $ una sola vez

Comparación de motores de renderizado HTML

Aspose.PDF utiliza el motor CSS Flying Saucer, que se enfrenta a los estándares web modernos.IronPDFutiliza el motor de renderizado Chromium:

CaracterísticaAspose.PDF (Platillo volante)IronPDF(Cromo)
Soporte CSS3Limitado (CSS antiguo)CSS3 completo
Flexbox/GridNo soportadoSoporte completo
JavaScriptMuy limitadoSoporte completo
Fuentes webParcialCompletar
HTML5 modernoLimitadoCompletar
Calidad de renderizadoVariablePixel-perfect

Problemas de rendimiento documentados

Los usuarios han informado de importantes diferencias de rendimiento entre las dos bibliotecas:

MétricaAspose.PDFIronPDF
Representación HTMLRalentizaciones documentadas (30 veces más lento en algunos casos)Motor Chromium optimizado
Documentos grandesProblemas de memoria notificadosTransmisión eficiente
Rendimiento de LinuxAltas fugas de CPU y memoriaEstable

Aspose.PDF frente a IronPDF: Diferencias clave

AspectoAspose.PDFIronPDF
Precios1.199 $/desarrollador/año (suscripción)749 $ por única vez (Lite)
Motor HTMLPlatillo volante (CSS limitado)Chromium (CSS3/JS completo)
RendimientoRalentizaciones documentadasOptimizado
Modelo de licenciaRenovación anual + archivo .licClave perpetua + basada en código
Soporte LinuxProblemas notificados (CPU, memoria)Estable
Indexación de páginasbasado en 1 (Páginas[1])basado en 0 (Páginas[0])

Preparación de la migración

Prerrequisitos

Asegúrese de que su entorno cumple estos requisitos:

  • .NET Framework 4.6.2+ o .NET Core 3.1 / .NET 5-9
  • Visual Studio 2019+ o VS Code con extensión de C#
  • Acceso al gestor de paquetes NuGet
  • Clave de licencia deIronPDF(prueba gratuita disponible en ironpdf.com)

Auditar el uso de Aspose.PDF

Ejecute estos comandos en su directorio de soluciones para identificar todas las referencias a Aspose.PDF:

# Find all Aspose.Pdf using statements
grep -r "using Aspose.Pdf" --include="*.cs" .

# Find HtmlLoadOptions usage
grep -r "HtmlLoadOptions\|HtmlFragment" --include="*.cs" .

# Find Facades usage
grep -r "PdfFileEditor\|PdfFileMend\|PdfFileStamp" --include="*.cs" .

# Find TextAbsorber usage
grep -r "TextAbsorber\|TextFragmentAbsorber" --include="*.cs" .
# Find all Aspose.Pdf using statements
grep -r "using Aspose.Pdf" --include="*.cs" .

# Find HtmlLoadOptions usage
grep -r "HtmlLoadOptions\|HtmlFragment" --include="*.cs" .

# Find Facades usage
grep -r "PdfFileEditor\|PdfFileMend\|PdfFileStamp" --include="*.cs" .

# Find TextAbsorber usage
grep -r "TextAbsorber\|TextFragmentAbsorber" --include="*.cs" .
SHELL

Cambios importantes que hay que anticipar

Patrón Aspose.PDFCambio requerido
nuevo Documento()+ Pages.Add()Utilizar el renderizado HTML
<código>HtmlLoadOptions</código<código>ChromePdfRenderer.RenderHtmlAsPdf()</código
TextFragment + posicionamiento manualPosicionamiento basado en CSS
<código>PdfFileEditor.Concatenate()</códigoPdfDocument.Merge()
<código>TextFragmentAbsorber</código<código>pdf.ExtractAllText()</código
<código>ImageStamp</códigoMarcas de agua basadas en HTML
licencias de archivos .licClave de licencia basada en código
indexación de páginas basada en 1indexación de páginas basada en 0

Proceso de migración paso a paso

Paso 1: Actualizar paquetes NuGet

Elimine Aspose.PDF e instale IronPDF:

# Remove Aspose.PDF
dotnet remove package Aspose.PDF

# Install IronPDF
dotnet add package IronPdf
# Remove Aspose.PDF
dotnet remove package Aspose.PDF

# Install IronPDF
dotnet add package IronPdf
SHELL

O a través de Package Manager Console:

Uninstall-Package Aspose.PDF
Install-Package IronPdf

Paso 2: Actualizar referencias de espacios de nombres

Sustituya los espacios de nombres Aspose.PDF por IronPDF:

// Remove these
using Aspose.Pdf;
using Aspose.Pdf.Text;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Generator;

// Add these
using IronPdf;
using IronPdf.Rendering;
using IronPdf.Editing;
// Remove these
using Aspose.Pdf;
using Aspose.Pdf.Text;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Generator;

// Add these
using IronPdf;
using IronPdf.Rendering;
using IronPdf.Editing;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Paso 3: Actualizar la configuración de la licencia

Aspose.PDF utiliza licencias de archivos .licensing.IronPDFutiliza una clave simple basada en código.

Implementación de Aspose.PDF:

var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

IronPdf.License.LicenseKey = "YOUR-IRONPDF-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-IRONPDF-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-IRONPDF-LICENSE-KEY"
$vbLabelText   $csharpLabel

Referencia completa de migración de API

Mapeo de clases principales

Clase Aspose.PDFEquivalente de IronPDFNotas
DocumentoDocumento PDFClase de documento principal
<código>HtmlLoadOptions</código<código>ChromePdfRenderer</códigoHTML a PDF
<código>TextFragmentAbsorber</código<código>PdfDocument.ExtractAllText()</códigoExtracción de texto
<código>PdfFileEditor</códigoPdfDocument.Merge()Operaciones de fusión/división
<código>TextStamp</código> / <código>ImageStamp</código><código>PdfDocument.ApplyWatermark()</códigoMarcas de agua
Licencia<código>Licencia.IronPdf</códigoLicencias

Operaciones de documentos

Método Aspose.PDFMétodo IronPDFNotas
nuevo Documento()nuevo PdfDocument()Documento vacío
nuevo Documento(ruta)<código>PdfDocument.FromFile(path)</códigoCargar desde archivo
doc.Guardar(ruta)<código>pdf.SaveAs(ruta)</códigoGuardar en archivo
doc.Pages.Count<código>pdf.PageCount</códigoNúmero de páginas
<código>doc.Pages.Delete(index)</código<código>pdf.RemovePage(index)</códigoEliminar página

Conversión de HTML a PDF

Método Aspose.PDFMétodo IronPDFNotas
<código>new HtmlLoadOptions()</código<código>new ChromePdfRenderer()</códigoRenderizador HTML
nuevo Documento(stream, htmlOptions)renderer.RenderHtmlAsPdf(html)Cadena HTML
nuevo Documento(ruta, htmlOpciones)<código>renderer.RenderHtmlFileAsPdf(ruta)</códigoArchivo HTML

Ejemplos de migración de código

Cadena HTML a PDF

La operación más común de Aspose.PDF demuestra la diferencia fundamental en el enfoque: Aspose.PDF requiere envolver HTML en un MemoryStream, mientras queIronPDFacepta cadenas directamente.

Implementación de Aspose.PDF:

// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlContent)))
        {
            var htmlLoadOptions = new HtmlLoadOptions();
            var document = new Document(stream, htmlLoadOptions);
            document.Save("output.pdf");
        }

        Console.WriteLine("PDF created from HTML string");
    }
}
// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlContent)))
        {
            var htmlLoadOptions = new HtmlLoadOptions();
            var document = new Document(stream, htmlLoadOptions);
            document.Save("output.pdf");
        }

        Console.WriteLine("PDF created from HTML string");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("output.pdf");

        Console.WriteLine("PDF created from HTML string");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        string htmlContent = "<html><body><h1>Hello World</h1><p>This is a PDF from HTML string.</p></body></html>";

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        pdf.SaveAs("output.pdf");

        Console.WriteLine("PDF created from HTML string");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF elimina por completo la envoltura MemoryStream: una API más limpia e intuitiva.

Archivo HTML a PDF

Implementación de Aspose.PDF:

// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var htmlLoadOptions = new HtmlLoadOptions();
        var document = new Document("input.html", htmlLoadOptions);
        document.Save("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var htmlLoadOptions = new HtmlLoadOptions();
        var document = new Document("input.html", htmlLoadOptions);
        document.Save("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlFileAsPdf("input.html");
        pdf.SaveAs("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlFileAsPdf("input.html");
        pdf.SaveAs("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Fusión de varios PDF

Aspose.PDF requiere recorrer las páginas manualmente.IronPDFproporciona un método estático Merge.

Implementación de Aspose.PDF:

// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var document1 = new Document("file1.pdf");
        var document2 = new Document("file2.pdf");

        foreach (Page page in document2.Pages)
        {
            document1.Pages.Add(page);
        }

        document1.Save("merged.pdf");
        Console.WriteLine("PDFs merged successfully");
    }
}
// NuGet: Install-Package Aspose.PDF
using Aspose.Pdf;
using System;

class Program
{
    static void Main()
    {
        var document1 = new Document("file1.pdf");
        var document2 = new Document("file2.pdf");

        foreach (Page page in document2.Pages)
        {
            document1.Pages.Add(page);
        }

        document1.Save("merged.pdf");
        Console.WriteLine("PDFs merged successfully");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

// NuGet: Install-Package IronPdf
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var pdf1 = PdfDocument.FromFile("file1.pdf");
        var pdf2 = PdfDocument.FromFile("file2.pdf");

        var merged = PdfDocument.Merge(pdf1, pdf2);
        merged.SaveAs("merged.pdf");

        Console.WriteLine("PDFs merged successfully");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var pdf1 = PdfDocument.FromFile("file1.pdf");
        var pdf2 = PdfDocument.FromFile("file2.pdf");

        var merged = PdfDocument.Merge(pdf1, pdf2);
        merged.SaveAs("merged.pdf");

        Console.WriteLine("PDFs merged successfully");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Extracción de texto

Implementación de Aspose.PDF:

using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");
var absorber = new TextAbsorber();

foreach (Page page in document.Pages)
{
    page.Accept(absorber);
}

string extractedText = absorber.Text;
Console.WriteLine(extractedText);
using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");
var absorber = new TextAbsorber();

foreach (Page page in document.Pages)
{
    page.Accept(absorber);
}

string extractedText = absorber.Text;
Console.WriteLine(extractedText);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Extract all text - one line!
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);

// Or extract from specific page
string page1Text = pdf.ExtractTextFromPage(0);
using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Extract all text - one line!
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);

// Or extract from specific page
string page1Text = pdf.ExtractTextFromPage(0);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF simplifica la extracción de texto de varios pasos a una única llamada a un método.

Añadir marcas de agua

Implementación de Aspose.PDF:

using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");

var textStamp = new TextStamp("CONFIDENTIAL");
textStamp.Background = true;
textStamp.XIndent = 100;
textStamp.YIndent = 100;
textStamp.Rotate = Rotation.on45;
textStamp.Opacity = 0.5;
textStamp.TextState.Font = FontRepository.FindFont("Arial");
textStamp.TextState.FontSize = 72;
textStamp.TextState.ForegroundColor = Color.Red;

foreach (Page page in document.Pages)
{
    page.AddStamp(textStamp);
}

document.Save("watermarked.pdf");
using Aspose.Pdf;
using Aspose.Pdf.Text;

var document = new Document("document.pdf");

var textStamp = new TextStamp("CONFIDENTIAL");
textStamp.Background = true;
textStamp.XIndent = 100;
textStamp.YIndent = 100;
textStamp.Rotate = Rotation.on45;
textStamp.Opacity = 0.5;
textStamp.TextState.Font = FontRepository.FindFont("Arial");
textStamp.TextState.FontSize = 72;
textStamp.TextState.ForegroundColor = Color.Red;

foreach (Page page in document.Pages)
{
    page.AddStamp(textStamp);
}

document.Save("watermarked.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

using IronPdf;
using IronPdf.Editing;

var pdf = PdfDocument.FromFile("document.pdf");

// HTML-based watermark with full styling control
string watermarkHtml = @"
<div style='
    color: red;
    opacity: 0.5;
    font-family: Arial;
    font-size: 72px;
    font-weight: bold;
    text-align: center;
'>CONFIDENTIAL</div>";

pdf.ApplyWatermark(watermarkHtml,
    rotation: 45,
    verticalAlignment: VerticalAlignment.Middle,
    horizontalAlignment: HorizontalAlignment.Center);

pdf.SaveAs("watermarked.pdf");
using IronPdf;
using IronPdf.Editing;

var pdf = PdfDocument.FromFile("document.pdf");

// HTML-based watermark with full styling control
string watermarkHtml = @"
<div style='
    color: red;
    opacity: 0.5;
    font-family: Arial;
    font-size: 72px;
    font-weight: bold;
    text-align: center;
'>CONFIDENTIAL</div>";

pdf.ApplyWatermark(watermarkHtml,
    rotation: 45,
    verticalAlignment: VerticalAlignment.Middle,
    horizontalAlignment: HorizontalAlignment.Center);

pdf.SaveAs("watermarked.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF utiliza marcas de agua basadas en HTML/CSS, lo que proporciona un control total del estilo mediante tecnologías web conocidas.

Protección con contraseña

Implementación de Aspose.PDF:

using Aspose.Pdf;

var document = new Document("document.pdf");
document.Encrypt("userPassword", "ownerPassword", DocumentPrivilege.ForbidAll, CryptoAlgorithm.AESx256);
document.Save("protected.pdf");
using Aspose.Pdf;

var document = new Document("document.pdf");
document.Encrypt("userPassword", "ownerPassword", DocumentPrivilege.ForbidAll, CryptoAlgorithm.AESx256);
document.Save("protected.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Implementación de IronPDF:

using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Set passwords
pdf.SecuritySettings.UserPassword = "userPassword";
pdf.SecuritySettings.OwnerPassword = "ownerPassword";

// Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;

pdf.SaveAs("protected.pdf");
using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

// Set passwords
pdf.SecuritySettings.UserPassword = "userPassword";
pdf.SecuritySettings.OwnerPassword = "ownerPassword";

// Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;

pdf.SaveAs("protected.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF proporciona un control granular sobre los permisos a través de propiedades fuertemente tipadas. Para más opciones, consulte la documentación sobre cifrado.

Cabeceras y pies de página

Implementación de IronPDF:

using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:12px;'>
            Company Header
        </div>",
    DrawDividerLine = true,
    MaxHeight = 30
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:10px;'>
            Page {page} of {total-pages}
        </div>",
    DrawDividerLine = true,
    MaxHeight = 25
};

var pdf = renderer.RenderHtmlAsPdf("<h1>Content here</h1>");
pdf.SaveAs("with_headers.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:12px;'>
            Company Header
        </div>",
    DrawDividerLine = true,
    MaxHeight = 30
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align:center; font-family:Arial; font-size:10px;'>
            Page {page} of {total-pages}
        </div>",
    DrawDividerLine = true,
    MaxHeight = 25
};

var pdf = renderer.RenderHtmlAsPdf("<h1>Content here</h1>");
pdf.SaveAs("with_headers.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF admite marcadores de posición como {page} y {total-pages} para la numeración dinámica de páginas. Para más opciones, consulte la documentación sobre encabezados y pies de página.

Notas de migración críticas

Cambio en la indexación de páginas

Aspose.PDF utiliza indexación basada en 1.IronPDFutiliza indexación basada en 0:

// Aspose.PDF - 1-based indexing
var firstPage = doc.Pages[1];  // First page
var thirdPage = doc.Pages[3];  // Third page

//IronPDF- 0-based indexing
var firstPage = pdf.Pages[0];  // First page
var thirdPage = pdf.Pages[2];  // Third page
// Aspose.PDF - 1-based indexing
var firstPage = doc.Pages[1];  // First page
var thirdPage = doc.Pages[3];  // Third page

//IronPDF- 0-based indexing
var firstPage = pdf.Pages[0];  // First page
var thirdPage = pdf.Pages[2];  // Third page
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Clave de archivo de licencia a código

Sustituya la licencia de archivos .lic por una activación basada en código:

// Aspose.PDF
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");

// IronPDF
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Or from environment variable
IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY");
// Aspose.PDF
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");

// IronPDF
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Or from environment variable
IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Integración con .NET Core

Patrón IronPDF:

[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>");

        return File(pdf.BinaryData, "application/pdf", "report.pdf");
    }

    [HttpGet("generate-async")]
    public async Task<IActionResult> GeneratePdfAsync()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>");

        return File(pdf.Stream, "application/pdf", "report.pdf");
    }
}
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>");

        return File(pdf.BinaryData, "application/pdf", "report.pdf");
    }

    [HttpGet("generate-async")]
    public async Task<IActionResult> GeneratePdfAsync()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>");

        return File(pdf.Stream, "application/pdf", "report.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Configuración de la inyección de dependencias

// Program.cs
public void ConfigureServices(IServiceCollection services)
{
    // Set license once
    IronPdf.License.LicenseKey = Configuration["IronPdf:LicenseKey"];

    // Register renderer as scoped service
    services.AddScoped<ChromePdfRenderer>();
}
// Program.cs
public void ConfigureServices(IServiceCollection services)
{
    // Set license once
    IronPdf.License.LicenseKey = Configuration["IronPdf:LicenseKey"];

    // Register renderer as scoped service
    services.AddScoped<ChromePdfRenderer>();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Optimización del rendimiento

// 1. Reuse renderer instance
private static readonly ChromePdfRenderer SharedRenderer = new ChromePdfRenderer();

// 2. Disable unnecessary features for speed
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false; // If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0);   // No delay
renderer.RenderingOptions.Timeout = 30000;          // 30s max

// 3. Proper disposal
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
    pdf.SaveAs("output.pdf");
}
// 1. Reuse renderer instance
private static readonly ChromePdfRenderer SharedRenderer = new ChromePdfRenderer();

// 2. Disable unnecessary features for speed
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false; // If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0);   // No delay
renderer.RenderingOptions.Timeout = 30000;          // 30s max

// 3. Proper disposal
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
    pdf.SaveAs("output.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Solución de problemas comunes de migración

Asunto: HtmlLoadOptions Not Found

Sustituir por ChromePdfRenderer:

// Remove this
var doc = new Document(stream, new HtmlLoadOptions());

// Use this
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);
// Remove this
var doc = new Document(stream, new HtmlLoadOptions());

// Use this
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Asunto: TextFragmentAbsorber Not Found

Utilice la extracción directa de texto:

// Remove this
var absorber = new TextFragmentAbsorber();
page.Accept(absorber);
string text = absorber.Text;

// Use this
var pdf = PdfDocument.FromFile("doc.pdf");
string text = pdf.ExtractAllText();
// Remove this
var absorber = new TextFragmentAbsorber();
page.Accept(absorber);
string text = absorber.Text;

// Use this
var pdf = PdfDocument.FromFile("doc.pdf");
string text = pdf.ExtractAllText();
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Edición: PdfFileEditor.Concatenate No Disponible

Utilice PdfDocument.Merge():

// Remove this
var editor = new PdfFileEditor();
editor.Concatenate(files, output);

// Use this
var pdfs = files.Select(PdfDocument.FromFile).ToList();
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs(output);
// Remove this
var editor = new PdfFileEditor();
editor.Concatenate(files, output);

// Use this
var pdfs = files.Select(PdfDocument.FromFile).ToList();
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs(output);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Lista de comprobación posterior a la migración

Después de completar la migración del código, verifique lo siguiente:

  • [ ] Eliminar archivos de licencia de Aspose.PDF (.lic)
  • [ ] Verificar la calidad de renderizado HTML (CSS Grid, Flexbox deberían funcionar correctamente)
  • [ ] Prueba de casos límite con documentos de gran tamaño y CSS complejo
  • [ ] Actualizar las referencias del índice de páginas (de 1 a 0)
  • [Actualizar las configuraciones de Docker, si procede
  • [ ] Actualizar las canalizaciones CI/CD con la nueva configuración de la clave de licencia
  • [ ] Documentar nuevos patrones para su equipo

Proteja su infraestructura PDF

Con .NET 10 en el horizonte y C# 14 introduciendo nuevas características del lenguaje, la elección de una biblioteca PDF con capacidades de renderizado modernas garantiza la compatibilidad con los estándares web en evolución. El motor Chromium deIronPDFrenderiza el mismo HTML/CSS que funciona en los navegadores modernos, lo que significa que sus plantillas PDF se mantienen actualizadas a medida que los proyectos se extienden hasta 2025 y 2026, sin las limitaciones CSS del motor Flying Saucer de Aspose.PDF.

Recursos adicionales


La migración de Aspose.PDF aIronPDFtransforma su código PDF de un motor de renderizado HTML obsoleto a un renderizado moderno basado en Chromium. La eliminación de los envoltorios MemoryStream, la extracción de texto simplificada y la compatibilidad superior con CSS3 ofrecen un aumento inmediato de la productividad, al tiempo que reducen los costes de licencia a largo plazo de suscripciones anuales a una inversión única.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más