Passer au contenu du pied de page
GUIDES DE MIGRATION

Migrer d'ActivePDF à IronPDF : (Guide .NET)

ActivePDF est un outil PDF fiable pour les développeurs .NET. Cependant, depuis son rachat par Foxit, de nombreuses équipes de développement sont incertaines quant à l'avenir de la plateforme, aux conditions de licence et à son développement en cours. Ce guide propose une procédure de migration détaillée, étape par étape, d'ActivePDF vers IronPDF, une bibliothèque PDF .NET moderne et activement maintenue, prenant en charge .NET Framework 4.6.2 jusqu'à .NET 9 et versions ultérieures.

Pourquoi envisager de changer de solution ?

L'acquisition d'ActivePDF par Foxit a engendré plusieurs défis pour les développeurs travaillant sur des solutions de génération et de manipulation de PDF dans les applications .NET.

Avenir incertain du produit

Le passage d'ActivePDF sous la direction de Foxit soulève des questions quant à l'avenir du développement de cet outil. Les développeurs qui utilisent ActivePDFs'exposent à des risques potentiels de dégradation de la bibliothèque, avec une réduction du support et un développement stagnant. Pour les équipes qui planifient des projets s'étendant jusqu'en 2025 et 2026, cette incertitude crée un risque technique important.

Complications liées à la licence

L'acquisition a introduit des incertitudes en matière de licence qui peuvent compliquer les déploiements. Le modèle de licence traditionnel d'ActivePDF, verrouillé par la machine, crée des frictions dans les environnements cloud et conteneurisés modernes où les applications évoluent de manière dynamique à travers l'infrastructure.

Modèles d'architecture de Legacy

L'architecture d'ActivePDF reflète une ancienne philosophie de conception centrée sur les modèles de boîtes à outils avec état. Le flux de travail OpenOutputFile/CloseOutputFile nécessite une gestion explicite des poignées de fichiers qui ne s'aligne pas sur les conventions C# modernes et peut introduire des problèmes de gestion des ressources s'il n'est pas manipulé avec précaution.

Installation et frais généraux de configuration

Contrairement à la gestion contemporaine des packages basée sur NuGet, ActivePDFnécessite souvent des références DLL manuelles et une configuration explicite du chemin d'accès lors de l'instanciation de la boîte à outils - un schéma qui augmente les frictions d'intégration et complique les pipelines CI/CD.

ActivePDFvs.IronPDF: Principales différences

Avant de commencer le processus de migration, comprendre les différences fondamentales entre ActivePDFetIronPDFpermet de mieux appréhender les modifications de code nécessaires.

Aspect ActivePDF IronPDF
Situation de l'entreprise Acquis par Foxit (avenir incertain) Feuille de route de développement claire et indépendante
Installation Références DLL manuelles Simple Paquet NuGet
Modèle d'interface utilisateur Stateful (OpenOutputFile/CloseOutputFile) API fluide et fonctionnelle
Modèle de licence Verrouillé Clé basée sur le code
Support .NET Focus sur l'ancien .NET Framework Framework 4.6.2 vers .NET 9+
Gestion des erreurs Codes de retour des entiers Moderne, basé sur les exceptions
Support asynchrone Non disponible Prise en charge complète de l'asynchronisme et de l'attente

Préparation de la migration

Auditez votre base de code

Avant de commencer la migration, identifiez toutes les utilisations d'ActivePDF dans votre solution. Exécutez ces commandes dans votre répertoire de solutions :

grep -r "using ActivePDF" --include="*.cs" .
grep -r "using APToolkitNET" --include="*.cs" .
grep -r "APToolkitNET" --include="*.csproj" .
grep -r "using ActivePDF" --include="*.cs" .
grep -r "using APToolkitNET" --include="*.cs" .
grep -r "APToolkitNET" --include="*.csproj" .
SHELL

Rupture de document

Comprendre les différences fondamentales entre les API permet de planifier votre stratégie de migration :

Catégorie Comportement d'ActivePDF Comportement d'IronPDF Action de migration
Modèle d'objet Objet Toolkit unique ChromePdfRenderer + PdfDocument Des préoccupations distinctes
Opérations sur les fichiers OpenOutputFile()/CloseOutputFile() Direct SaveAs() Supprimer les appels d'ouverture/fermeture
Création de pages méthode NewPage() Automatique à partir de HTML Supprimer les appels à la création de pages
Valeurs de retour Codes d'erreur des nombres entiers Exceptions Implémenter try/catch
Taille de la page Unités Points (612x792 = Lettre) Enums ou millimètres Mesures de mise à jour

Prérequis

Assurez-vous que votre environnement répond à ces exigences :

  • .NET Framework 4.6.2+ ou .NET Core 3.1 / .NET 5-9
  • Visual Studio 2019+ ou JetBrains Rider
  • Accès au gestionnaire de paquets NuGet
  • Clé de licenceIronPDF(essai gratuit disponible sur ironpdf.com)

Processus de migration étape par étape

Étape 1 : Mise à jour des paquets NuGet

Supprimez le paquet ActivePDFet installezIronPDF:

# Remove ActivePDFpackage
dotnet remove package APToolkitNET

# Install IronPDF
dotnet add package IronPdf
# Remove ActivePDFpackage
dotnet remove package APToolkitNET

# Install IronPDF
dotnet add package IronPdf
SHELL

Alternativement, via la console Visual Studio Package Manager :

Uninstall-Package APToolkitNET
Install-Package IronPdf

Pour les projets comportant des références DLL manuelles, supprimez la référence de votre fichier .csproj :

<!-- Remove this block -->
<Reference Include="APToolkitNET">
    <HintPath>path\to\APToolkitNET.dll</HintPath>
</Reference>
<!-- Remove this block -->
<Reference Include="APToolkitNET">
    <HintPath>path\to\APToolkitNET.dll</HintPath>
</Reference>
XML

Étape 2 : configuration de la clé de licence

Ajoutez la clé de licenceIronPDFau démarrage de l'application, avant toute opération sur les PDF :

// Add at application startup (Program.cs or Startup.cs)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

// Verify license status
bool isLicensed = IronPdf.License.IsLicensed;
// Add at application startup (Program.cs or Startup.cs)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

// Verify license status
bool isLicensed = IronPdf.License.IsLicensed;
$vbLabelText   $csharpLabel

Étape 3 : mise à jour des références aux espaces de noms

Effectuez une recherche et un remplacement globaux dans votre solution :

Recherche Remplacer par
utilisant ActivePDF.Toolkit; utiliser IronPdf;
utilisant APToolkitNET; utiliser IronPdf;
utilisant APToolkitNET.PDFObjects; utiliser IronPdf;
utilisant APToolkitNET.Common; utiliser IronPdf;

Référence complète de migration des API

Méthodes de création de documents

Méthode ActivePDF Équivalent d'IronPDF Notes
new Toolkit() new ChromePdfRenderer() Le moteur de rendu crée des PDF
toolkit.OpenOutputFile(path) Aucun équivalent n'est nécessaire Il suffit d'appeler SaveAs() à la fin
toolkit.CloseOutputFile() Aucun équivalent n'est nécessaire Nettoyage automatique
toolkit.AddHTML(html) renderer.RenderHtmlAsPdf(html) Retourne PdfDocument
toolkit.AddURL(url) renderer.RenderUrlAsPdf(url) Conversion d'URL en PDF
toolkit.SaveAs(path) pdf.SaveAs(path) Enregistrer dans un fichier

Opérations de fichiers

Méthode ActivePDF Équivalent d'IronPDF Notes
toolkit.OpenInputFile(path) PdfDocument.FromFile(path) Charger le PDF existant
toolkit.AddPDF(path) PdfDocument.Merge() Pour les opérations de fusion
toolkit.GetPageCount() pdf.PageCount Accès à la propriété
toolkit.GetText() pdf.ExtractAllText() Extraction de texte

Configuration de la page

Méthode ActivePDF Équivalent d'IronPDF
toolkit.SetPageSize(612, 792) RenderingOptions.PaperSize = PdfPaperSize.Letter
toolkit.SetOrientation("Landscape") RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape
toolkit.SetMargins(t, b, l, r) RenderingOptions.MarginTop/Bottom/Left/Right

Méthodes de sécurité

Méthode ActivePDF Équivalent d'IronPDF
toolkit.Encrypt(password) pdf.SecuritySettings.OwnerPassword
toolkit.SetUserPassword(pwd) pdf.SecuritySettings.UserPassword
toolkit.SetPermissions(flags) pdf.SecuritySettings.AllowUserXxx
toolkit.AddWatermark(text) pdf.ApplyWatermark(html)

Exemples de migration de code

Conversion HTML en PDF

La conversion de chaînes HTML en documents PDF représente l'un des scénarios de génération de PDF les plus courants. Voici comment le code se transforme au cours de la migration.

Mise en œuvre d'ActivePDF:

// NuGet: Install-Package APToolkitNET
using ActivePDF.Toolkit;
using System;

class Program
{
    static void Main()
    {
        Toolkit toolkit = new Toolkit();

        string htmlContent = "<html><body><h1>Hello World</h1></body></html>";

        if (toolkit.OpenOutputFile("output.pdf") == 0)
        {
            toolkit.AddHTML(htmlContent);
            toolkit.CloseOutputFile();
            Console.WriteLine("PDF created successfully");
        }
    }
}
// NuGet: Install-Package APToolkitNET
using ActivePDF.Toolkit;
using System;

class Program
{
    static void Main()
    {
        Toolkit toolkit = new Toolkit();

        string htmlContent = "<html><body><h1>Hello World</h1></body></html>";

        if (toolkit.OpenOutputFile("output.pdf") == 0)
        {
            toolkit.AddHTML(htmlContent);
            toolkit.CloseOutputFile();
            Console.WriteLine("PDF created successfully");
        }
    }
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

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

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();

        string htmlContent = "<html><body><h1>Hello World</h1></body></html>";

        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        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();

        string htmlContent = "<html><body><h1>Hello World</h1></body></html>";

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

        Console.WriteLine("PDF created successfully");
    }
}
$vbLabelText   $csharpLabel

L'approcheIronPDFélimine la gestion explicite des poignées de fichiers tout en fournissant un code plus propre et plus lisible. Pour les scénarios avancés HTML vers PDF, le ChromePdfRenderer d'IronPDF utilise un moteur de rendu basé sur Chromium pour une prise en charge CSS et JavaScript parfaite au pixel près.

Conversion d'URL en PDF

La capture de pages web en tant que documents PDF suit un modèle de modernisation similaire.

Mise en œuvre d'ActivePDF:

using ActivePDF.Toolkit;
using System;

class Program
{
    static void Main()
    {
        Toolkit toolkit = new Toolkit();

        string url = "https://www.example.com";

        if (toolkit.OpenOutputFile("webpage.pdf") == 0)
        {
            toolkit.AddURL(url);
            toolkit.CloseOutputFile();
            Console.WriteLine("PDF from URL created successfully");
        }
    }
}
using ActivePDF.Toolkit;
using System;

class Program
{
    static void Main()
    {
        Toolkit toolkit = new Toolkit();

        string url = "https://www.example.com";

        if (toolkit.OpenOutputFile("webpage.pdf") == 0)
        {
            toolkit.AddURL(url);
            toolkit.CloseOutputFile();
            Console.WriteLine("PDF from URL created successfully");
        }
    }
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();

        string url = "https://www.example.com";

        var pdf = renderer.RenderUrlAsPdf(url);
        pdf.SaveAs("webpage.pdf");

        Console.WriteLine("PDF from URL created successfully");
    }
}
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();

        string url = "https://www.example.com";

        var pdf = renderer.RenderUrlAsPdf(url);
        pdf.SaveAs("webpage.pdf");

        Console.WriteLine("PDF from URL created successfully");
    }
}
$vbLabelText   $csharpLabel

Fusionner plusieurs fichiers PDF

La combinaison de plusieurs documents PDF en un seul fichier démontre l'approche fonctionnelle d'IronPDF en matière de manipulation de documents.

Mise en œuvre d'ActivePDF:

using ActivePDF.Toolkit;
using System;

class Program
{
    static void Main()
    {
        Toolkit toolkit = new Toolkit();

        if (toolkit.OpenOutputFile("merged.pdf") == 0)
        {
            toolkit.AddPDF("document1.pdf");
            toolkit.AddPDF("document2.pdf");
            toolkit.CloseOutputFile();
            Console.WriteLine("PDFs merged successfully");
        }
    }
}
using ActivePDF.Toolkit;
using System;

class Program
{
    static void Main()
    {
        Toolkit toolkit = new Toolkit();

        if (toolkit.OpenOutputFile("merged.pdf") == 0)
        {
            toolkit.AddPDF("document1.pdf");
            toolkit.AddPDF("document2.pdf");
            toolkit.CloseOutputFile();
            Console.WriteLine("PDFs merged successfully");
        }
    }
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;
using System;
using System.Collections.Generic;

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

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

        Console.WriteLine("PDFs merged successfully");
    }
}
using IronPdf;
using System;
using System.Collections.Generic;

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

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

        Console.WriteLine("PDFs merged successfully");
    }
}
$vbLabelText   $csharpLabel

Pour des scénarios de fusion plus avancés, notamment l'extraction sélective de pages, voir la documentation de fusion IronPDF.

Ajouter des en-têtes et des pieds de page

Mise en œuvre d'ActivePDF:

using ActivePDF.Toolkit;

public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenOutputFile(outputPath) == 0)
    {
        toolkit.SetHeader("My Document", 12, "Arial");
        toolkit.SetFooter("Page %p of %P", 10, "Arial");
        toolkit.AddHTML(html);
        toolkit.CloseOutputFile();
    }
}
using ActivePDF.Toolkit;

public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenOutputFile(outputPath) == 0)
    {
        toolkit.SetHeader("My Document", 12, "Arial");
        toolkit.SetFooter("Page %p of %P", 10, "Arial");
        toolkit.AddHTML(html);
        toolkit.CloseOutputFile();
    }
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;

public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
    var renderer = new ChromePdfRenderer();

    renderer.RenderingOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "My Document",
        FontSize = 12,
        FontFamily = "Arial"
    };

    renderer.RenderingOptions.TextFooter = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        FontSize = 10,
        FontFamily = "Arial"
    };

    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(outputPath);
}
using IronPdf;

public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
    var renderer = new ChromePdfRenderer();

    renderer.RenderingOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "My Document",
        FontSize = 12,
        FontFamily = "Arial"
    };

    renderer.RenderingOptions.TextFooter = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        FontSize = 10,
        FontFamily = "Arial"
    };

    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(outputPath);
}
$vbLabelText   $csharpLabel

IronPDF prend en charge les en-têtes et pieds de page textuels et HTML, offrant ainsi une flexibilité de conception totale.

Protection des mots de passe et sécurité

Mise en œuvre d'ActivePDF:

using ActivePDF.Toolkit;

public void ProtectPdf(string inputPath, string outputPath, string password)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenInputFile(inputPath) == 0)
    {
        toolkit.Encrypt(password);
        toolkit.SetUserPassword(password);
        toolkit.SetPermissions(4); // Print only
        toolkit.SaveAs(outputPath);
        toolkit.CloseInputFile();
    }
}
using ActivePDF.Toolkit;

public void ProtectPdf(string inputPath, string outputPath, string password)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenInputFile(inputPath) == 0)
    {
        toolkit.Encrypt(password);
        toolkit.SetUserPassword(password);
        toolkit.SetPermissions(4); // Print only
        toolkit.SaveAs(outputPath);
        toolkit.CloseInputFile();
    }
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;

public void ProtectPdf(string inputPath, string outputPath, string password)
{
    using var pdf = PdfDocument.FromFile(inputPath);

    pdf.SecuritySettings.OwnerPassword = password;
    pdf.SecuritySettings.UserPassword = password;
    pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
    pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;

    pdf.SaveAs(outputPath);
}
using IronPdf;

public void ProtectPdf(string inputPath, string outputPath, string password)
{
    using var pdf = PdfDocument.FromFile(inputPath);

    pdf.SecuritySettings.OwnerPassword = password;
    pdf.SecuritySettings.UserPassword = password;
    pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
    pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;

    pdf.SaveAs(outputPath);
}
$vbLabelText   $csharpLabel

L'API paramètres de sécurité d'IronPDF permet un contrôle granulaire des autorisations sur les documents à l'aide d'enums fortement typés au lieu de drapeaux entiers.

Extraction de texte

Mise en œuvre d'ActivePDF:

using ActivePDF.Toolkit;

public string ExtractText(string pdfPath)
{
    Toolkit toolkit = new Toolkit();
    string text = "";

    if (toolkit.OpenInputFile(pdfPath) == 0)
    {
        int pageCount = toolkit.GetPageCount();
        for (int i = 1; i <= pageCount; i++)
        {
            text += toolkit.GetTextFromPage(i) + "\n";
        }
        toolkit.CloseInputFile();
    }

    return text;
}
using ActivePDF.Toolkit;

public string ExtractText(string pdfPath)
{
    Toolkit toolkit = new Toolkit();
    string text = "";

    if (toolkit.OpenInputFile(pdfPath) == 0)
    {
        int pageCount = toolkit.GetPageCount();
        for (int i = 1; i <= pageCount; i++)
        {
            text += toolkit.GetTextFromPage(i) + "\n";
        }
        toolkit.CloseInputFile();
    }

    return text;
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;

public string ExtractText(string pdfPath)
{
    using var pdf = PdfDocument.FromFile(pdfPath);
    return pdf.ExtractAllText();
}
using IronPdf;

public string ExtractText(string pdfPath)
{
    using var pdf = PdfDocument.FromFile(pdfPath);
    return pdf.ExtractAllText();
}
$vbLabelText   $csharpLabel

La mise en œuvre d'IronPDF réduit l'extraction de texte de plusieurs lignes à un seul appel de méthode.

Ajouter des filigranes

Mise en œuvre d'ActivePDF:

using ActivePDF.Toolkit;

public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenInputFile(inputPath) == 0)
    {
        int pageCount = toolkit.GetPageCount();
        for (int i = 1; i <= pageCount; i++)
        {
            toolkit.SetPage(i);
            toolkit.AddWatermark(watermarkText, 45, 0.5f);
        }
        toolkit.SaveAs(outputPath);
        toolkit.CloseInputFile();
    }
}
using ActivePDF.Toolkit;

public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenInputFile(inputPath) == 0)
    {
        int pageCount = toolkit.GetPageCount();
        for (int i = 1; i <= pageCount; i++)
        {
            toolkit.SetPage(i);
            toolkit.AddWatermark(watermarkText, 45, 0.5f);
        }
        toolkit.SaveAs(outputPath);
        toolkit.CloseInputFile();
    }
}
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;

public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
    using var pdf = PdfDocument.FromFile(inputPath);

    pdf.ApplyWatermark(
        $"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
        rotation: 45,
        opacity: 50);

    pdf.SaveAs(outputPath);
}
using IronPdf;

public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
    using var pdf = PdfDocument.FromFile(inputPath);

    pdf.ApplyWatermark(
        $"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
        rotation: 45,
        opacity: 50);

    pdf.SaveAs(outputPath);
}
$vbLabelText   $csharpLabel

Le filigrane basé sur le HTML d'IronPDF permet un style CSS pour un contrôle complet de la conception sans itération page par page.

Intégration d'ASP.NET Core

Les applications web modernes bénéficient considérablement des modèles d'intégration plus propres d'IronPDF.

Modèle ActivePDF:

[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenOutputFile("temp.pdf") == 0)
    {
        toolkit.AddHTML(request.Html);
        toolkit.CloseOutputFile();

        byte[] bytes = System.IO.File.ReadAllBytes("temp.pdf");
        return File(bytes, "application/pdf", "report.pdf");
    }

    return BadRequest("PDF generation failed");
}
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
    Toolkit toolkit = new Toolkit();

    if (toolkit.OpenOutputFile("temp.pdf") == 0)
    {
        toolkit.AddHTML(request.Html);
        toolkit.CloseOutputFile();

        byte[] bytes = System.IO.File.ReadAllBytes("temp.pdf");
        return File(bytes, "application/pdf", "report.pdf");
    }

    return BadRequest("PDF generation failed");
}
$vbLabelText   $csharpLabel

Modèle IronPDF:

[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
    var renderer = new ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(request.Html);

    return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
    var renderer = new ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(request.Html);

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

IronPDF élimine le besoin de fichiers temporaires, renvoyant les données binaires du PDF directement depuis la mémoire.

Support asynchrone pour les applications Web

ActivePDF n'a pas de support asynchrone natif.IronPDFoffre des fonctionnalités asynchrones/await complètes, essentielles pour les applications web évolutives :

using IronPdf;

public async Task<byte[]> GeneratePdfAsync(string html)
{
    var renderer = new ChromePdfRenderer();
    using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
    return pdf.BinaryData;
}
using IronPdf;

public async Task<byte[]> GeneratePdfAsync(string html)
{
    var renderer = new ChromePdfRenderer();
    using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
    return pdf.BinaryData;
}
$vbLabelText   $csharpLabel

Configuration de l'injection de dépendance

Pour les applications .NET 6+, enregistrez les servicesIronPDFdans votre conteneur DI :

// Program.cs (.NET 6+)
builder.Services.AddSingleton<ChromePdfRenderer>();

// Service wrapper
public interface IPdfService
{
    Task<byte[]> GeneratePdfAsync(string html);
    Task<byte[]> GeneratePdfFromUrlAsync(string url);
}

public class IronPdfService : IPdfService
{
    private readonly ChromePdfRenderer _renderer;

    public IronPdfService()
    {
        _renderer = new ChromePdfRenderer();
        _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
    }

    public async Task<byte[]> GeneratePdfAsync(string html)
    {
        using var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        return pdf.BinaryData;
    }

    public async Task<byte[]> GeneratePdfFromUrlAsync(string url)
    {
        using var pdf = await _renderer.RenderUrlAsPdfAsync(url);
        return pdf.BinaryData;
    }
}
// Program.cs (.NET 6+)
builder.Services.AddSingleton<ChromePdfRenderer>();

// Service wrapper
public interface IPdfService
{
    Task<byte[]> GeneratePdfAsync(string html);
    Task<byte[]> GeneratePdfFromUrlAsync(string url);
}

public class IronPdfService : IPdfService
{
    private readonly ChromePdfRenderer _renderer;

    public IronPdfService()
    {
        _renderer = new ChromePdfRenderer();
        _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
    }

    public async Task<byte[]> GeneratePdfAsync(string html)
    {
        using var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
        return pdf.BinaryData;
    }

    public async Task<byte[]> GeneratePdfFromUrlAsync(string url)
    {
        using var pdf = await _renderer.RenderUrlAsPdfAsync(url);
        return pdf.BinaryData;
    }
}
$vbLabelText   $csharpLabel

Migration du traitement des erreurs

ActivePDF utilise des codes de retour entiers nécessitant des tables de consultation.IronPDFutilise une gestion moderne des exceptions :

Gestion des erreurs d'ActivePDF:

Toolkit toolkit = new Toolkit();
int result = toolkit.OpenOutputFile(path);

if (result != 0)
{
    // Error - need to look up error code
    Console.WriteLine($"Error code: {result}");
}
Toolkit toolkit = new Toolkit();
int result = toolkit.OpenOutputFile(path);

if (result != 0)
{
    // Error - need to look up error code
    Console.WriteLine($"Error code: {result}");
}
$vbLabelText   $csharpLabel

Gestion des erreurs IronPDF:

try
{
    var renderer = new ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(path);
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
    Console.WriteLine($"IronPDF Error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"General Error: {ex.Message}");
}
try
{
    var renderer = new ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(path);
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
    Console.WriteLine($"IronPDF Error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"General Error: {ex.Message}");
}
$vbLabelText   $csharpLabel

Conseils d'optimisation des performances

Réutiliser l'instance du moteur de rendu

La création d'un nouveau ChromePdfRenderer entraîne des frais généraux d'initialisation. Pour les opérations par lots, réutilisez une seule instance :

var renderer = new ChromePdfRenderer();
foreach (var html in htmlList)
{
    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs($"output_{i}.pdf");
}
var renderer = new ChromePdfRenderer();
foreach (var html in htmlList)
{
    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs($"output_{i}.pdf");
}
$vbLabelText   $csharpLabel

Utiliser Async dans les applications Web

Pour les applications ASP.NET Core, la génération asynchrone de PDF permet d'améliorer le débit :

public async Task<IActionResult> GenerateReport()
{
    var renderer = new ChromePdfRenderer();
    using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
    return File(pdf.BinaryData, "application/pdf");
}
public async Task<IActionResult> GenerateReport()
{
    var renderer = new ChromePdfRenderer();
    using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
    return File(pdf.BinaryData, "application/pdf");
}
$vbLabelText   $csharpLabel

Élimination correcte des ressources

Utilisez toujours des déclarations utilisant pour garantir un nettoyage adéquat :

using var pdf = renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
using var pdf = renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
$vbLabelText   $csharpLabel

Compression d'images

Réduisez la taille des fichiers de sortie grâce à la compression d'images :

using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.CompressImages(85); // 85% quality
pdf.SaveAs("compressed.pdf");
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.CompressImages(85); // 85% quality
pdf.SaveAs("compressed.pdf");
$vbLabelText   $csharpLabel

Dépannage des problèmes de migration courants

Sujet : Différences de taille de page

ActivePDF utilise des points (612x792 = Lettre), tandis qu'IronPDF utilise des enums ou des millimètres :

// ActivePDF: Points
toolkit.SetPageSize(612, 792);

// IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
// Or custom in mm:
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(215.9, 279.4);
// ActivePDF: Points
toolkit.SetPageSize(612, 792);

// IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
// Or custom in mm:
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(215.9, 279.4);
$vbLabelText   $csharpLabel

Sujet : Équivalent de CloseOutputFile manquant

IronPDF utilise un paradigme moderne sans gestion explicite des poignées de fichiers :

// ActivePDF
toolkit.OpenOutputFile(path);
toolkit.AddHTML(html);
toolkit.CloseOutputFile(); // Required!

//IronPDF- no open/close needed
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(path); // 'using' handles cleanup
// ActivePDF
toolkit.OpenOutputFile(path);
toolkit.AddHTML(html);
toolkit.CloseOutputFile(); // Required!

//IronPDF- no open/close needed
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(path); // 'using' handles cleanup
$vbLabelText   $csharpLabel

Sujet : PDF Rendus vides

Si le contenu dépendant de JavaScript s'affiche en blanc, configurez des délais de rendu :

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.RenderDelay(2000);
// Or wait for element:
renderer.RenderingOptions.WaitFor.HtmlElementById("content-loaded");
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.RenderDelay(2000);
// Or wait for element:
renderer.RenderingOptions.WaitFor.HtmlElementById("content-loaded");
$vbLabelText   $csharpLabel

Sujet : CSS/Images non chargées

Configurez l'URL de base pour la résolution des chemins relatifs :

renderer.RenderingOptions.BaseUrl = new Uri("https://yourdomain.com/assets/");
renderer.RenderingOptions.BaseUrl = new Uri("https://yourdomain.com/assets/");
$vbLabelText   $csharpLabel

Liste de contrôle post-migration

Après avoir effectué la migration du code, vérifiez les points suivants :

  • Exécuter tous les tests unitaires et d'intégration existants
  • Comparer visuellement les fichiers PDF générés avec les versions précédentes
  • Tester tous les flux de travail PDF dans un environnement de test
  • Vérifier que la licence fonctionne correctement ( IronPdf.License.IsLicensed )
  • Comparer les performances avec l'implémentation précédente
  • Supprimer les anciens fichiers d'installation d'ActivePDF et les références DLL
  • Mettre à jour les dépendances du pipeline CI/CD
  • ModèlesIronPDFà documenter pour votre équipe de développement

La pérennité de votre solution PDF

Avec .NET 10 à l'horizon et C# 14 introduisant de nouvelles fonctionnalités de langage, le choix d'une bibliothèque PDF .NET avec un développement actif garantit que vos applications restent compatibles avec les capacités d'exécution en constante évolution. L'engagement d'IronPDF à prendre en charge les dernières versions de .NET signifie que votre investissement dans la migration porte ses fruits lorsque vos projets s'étendent jusqu'en 2025 et 2026.

Ressources supplémentaires


La migration d'ActivePDF versIronPDFmodernise votre infrastructure de génération de PDF grâce à des API plus propres, une meilleure intégration .NET et un support actif à long terme. L'investissement dans la migration est rentabilisé par l'amélioration de la maintenabilité du code, les capacités asynchrones et la confiance dans le développement continu de votre bibliothèque PDF.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite