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 cette boîte à outils. 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 CloseOutputFile nécessite une gestion explicite des descripteurs de fichiers qui ne correspond pas aux conventions modernes de C# et peut introduire des problèmes de gestion des ressources s'il n'est pas géré avec soin.
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 ActivePDFet IronPDF permet 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 | Avec état (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" .
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 unique Toolkit |
ChromePdfRenderer + PdfDocument |
Des préoccupations distinctes |
| Opérations sur les fichiers | CloseOutputFile() |
Direct SaveAs() |
Supprimer les appels d'ouverture/fermeture |
| Création de pages | NewPage() méthode |
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 Package Manager NuGet
- Clé de licence IronPDF(essai gratuit disponible sur ironpdf.com)
Processus de migration étape par étape
Étape 1 : Mise à jour des paquets NuGet
Supprimez le paquet ActivePDFet installez IronPDF:
# Remove ActivePDFpackage
dotnet remove package APToolkitNET
# Install IronPDF
dotnet add package IronPdf
# Remove ActivePDFpackage
dotnet remove package APToolkitNET
# Install IronPDF
dotnet add package IronPdf
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 :
<Reference Include="APToolkitNET">
<HintPath>path\to\APToolkitNET.dll</HintPath>
</Reference>
<Reference Include="APToolkitNET">
<HintPath>path\to\APToolkitNET.dll</HintPath>
</Reference>
Étape 2 : configuration de la clé de licence
Ajoutez la clé de licence IronPDF au 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;
' Add at application startup (Program.vb or Startup.vb)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
' Verify license status
Dim isLicensed As Boolean = IronPdf.License.IsLicensed
É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 |
|---|---|
using ActivePDF.Toolkit; |
using IronPdf; |
using APToolkitNET; |
using IronPdf; |
using APToolkitNET.PDFObjects; |
using IronPdf; |
using APToolkitNET.Common; |
using IronPdf; |
Référence complète de migration des API
Méthodes de création de documents
| Méthode ActivePDF | Équivalent d'IronPDF |
|---|---|
new Toolkit() |
new ChromePdfRenderer() |
toolkit.OpenOutputFile(path) |
Aucun équivalent n'est nécessaire |
toolkit.CloseOutputFile() |
Aucun équivalent n'est nécessaire |
toolkit.AddHTML(html) |
renderer.RenderHtmlAsPdf(html) |
toolkit.AddURL(url) |
renderer.RenderUrlAsPdf(url) |
toolkit.SaveAs(path) |
pdf.SaveAs(path) |
Opérations de fichiers
| Méthode ActivePDF | Équivalent d'IronPDF |
|---|---|
toolkit.OpenInputFile(path) |
PdfDocument.FromFile(path) |
toolkit.AddPDF(path) |
PdfDocument.Merge() |
toolkit.GetPageCount() |
pdf.PageCount |
toolkit.GetText() |
pdf.ExtractAllText() |
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");
}
}
}
Imports ActivePDF.Toolkit
Imports System
Class Program
Shared Sub Main()
Dim toolkit As New Toolkit()
Dim htmlContent As String = "<html><body><h1>Hello World</h1></body></html>"
If toolkit.OpenOutputFile("output.pdf") = 0 Then
toolkit.AddHTML(htmlContent)
toolkit.CloseOutputFile()
Console.WriteLine("PDF created successfully")
End If
End Sub
End Class
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");
}
}
Imports IronPdf
Imports System
Module Program
Sub Main()
Dim renderer As New ChromePdfRenderer()
Dim htmlContent As String = "<html><body><h1>Hello World</h1></body></html>"
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF created successfully")
End Sub
End Module
L'approche IronPDF é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 de conversion HTML vers PDF , IronPDF utilise un moteur de rendu basé sur Chromium pour une prise en charge CSS et JavaScript 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");
}
}
}
Imports ActivePDF.Toolkit
Imports System
Class Program
Shared Sub Main()
Dim toolkit As New Toolkit()
Dim url As String = "https://www.example.com"
If toolkit.OpenOutputFile("webpage.pdf") = 0 Then
toolkit.AddURL(url)
toolkit.CloseOutputFile()
Console.WriteLine("PDF from URL created successfully")
End If
End Sub
End Class
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");
}
}
Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim url As String = "https://www.example.com"
Dim pdf = renderer.RenderUrlAsPdf(url)
pdf.SaveAs("webpage.pdf")
Console.WriteLine("PDF from URL created successfully")
End Sub
End Class
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");
}
}
}
Imports ActivePDF.Toolkit
Imports System
Class Program
Shared Sub Main()
Dim toolkit As New Toolkit()
If toolkit.OpenOutputFile("merged.pdf") = 0 Then
toolkit.AddPDF("document1.pdf")
toolkit.AddPDF("document2.pdf")
toolkit.CloseOutputFile()
Console.WriteLine("PDFs merged successfully")
End If
End Sub
End Class
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");
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim pdf1 = PdfDocument.FromFile("document1.pdf")
Dim pdf2 = PdfDocument.FromFile("document2.pdf")
Dim merged = PdfDocument.Merge(pdf1, pdf2)
merged.SaveAs("merged.pdf")
Console.WriteLine("PDFs merged successfully")
End Sub
End Module
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();
}
}
Imports ActivePDF.Toolkit
Public Sub CreatePdfWithHeaderFooter(html As String, outputPath As String)
Dim toolkit As New Toolkit()
If toolkit.OpenOutputFile(outputPath) = 0 Then
toolkit.SetHeader("My Document", 12, "Arial")
toolkit.SetFooter("Page %p of %P", 10, "Arial")
toolkit.AddHTML(html)
toolkit.CloseOutputFile()
End If
End Sub
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);
}
Imports IronPdf
Public Sub CreatePdfWithHeaderFooter(html As String, outputPath As String)
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.CenterText = "My Document",
.FontSize = 12,
.FontFamily = "Arial"
}
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.CenterText = "Page {page} of {total-pages}",
.FontSize = 10,
.FontFamily = "Arial"
}
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(outputPath)
End Using
End Sub
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();
}
}
Imports ActivePDF.Toolkit
Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
Dim toolkit As New Toolkit()
If toolkit.OpenInputFile(inputPath) = 0 Then
toolkit.Encrypt(password)
toolkit.SetUserPassword(password)
toolkit.SetPermissions(4) ' Print only
toolkit.SaveAs(outputPath)
toolkit.CloseInputFile()
End If
End Sub
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);
}
Imports IronPdf
Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
Using 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)
End Using
End Sub
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;
}
Imports ActivePDF.Toolkit
Public Function ExtractText(pdfPath As String) As String
Dim toolkit As New Toolkit()
Dim text As String = ""
If toolkit.OpenInputFile(pdfPath) = 0 Then
Dim pageCount As Integer = toolkit.GetPageCount()
For i As Integer = 1 To pageCount
text &= toolkit.GetTextFromPage(i) & vbCrLf
Next
toolkit.CloseInputFile()
End If
Return text
End Function
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();
}
Imports IronPdf
Public Function ExtractText(pdfPath As String) As String
Using pdf = PdfDocument.FromFile(pdfPath)
Return pdf.ExtractAllText()
End Using
End Function
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();
}
}
Imports ActivePDF.Toolkit
Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
Dim toolkit As New Toolkit()
If toolkit.OpenInputFile(inputPath) = 0 Then
Dim pageCount As Integer = toolkit.GetPageCount()
For i As Integer = 1 To pageCount
toolkit.SetPage(i)
toolkit.AddWatermark(watermarkText, 45, 0.5F)
Next
toolkit.SaveAs(outputPath)
toolkit.CloseInputFile()
End If
End Sub
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);
}
Imports IronPdf
Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
Using pdf = PdfDocument.FromFile(inputPath)
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation:=45,
opacity:=50)
pdf.SaveAs(outputPath)
End Using
End Sub
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");
}
<HttpPost>
Public Function GeneratePdf(<FromBody> request As ReportRequest) As IActionResult
Dim toolkit As New Toolkit()
If toolkit.OpenOutputFile("temp.pdf") = 0 Then
toolkit.AddHTML(request.Html)
toolkit.CloseOutputFile()
Dim bytes As Byte() = System.IO.File.ReadAllBytes("temp.pdf")
Return File(bytes, "application/pdf", "report.pdf")
End If
Return BadRequest("PDF generation failed")
End Function
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");
}
<HttpPost>
Public Function GeneratePdf(<FromBody> request As ReportRequest) As IActionResult
Dim renderer As New ChromePdfRenderer()
Using pdf = renderer.RenderHtmlAsPdf(request.Html)
Return File(pdf.BinaryData, "application/pdf", "report.pdf")
End Using
End Function
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. IronPDF offre 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;
}
Imports IronPdf
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte())
Dim renderer As New ChromePdfRenderer()
Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Configuration de l'injection de dépendance
Pour les applications .NET 6+, enregistrez les services IronPDF dans 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;
}
}
Imports Microsoft.Extensions.DependencyInjection
Imports System.Threading.Tasks
' Program.vb (.NET 6+)
builder.Services.AddSingleton(Of ChromePdfRenderer)()
' Service wrapper
Public Interface IPdfService
Function GeneratePdfAsync(html As String) As Task(Of Byte())
Function GeneratePdfFromUrlAsync(url As String) As Task(Of Byte())
End Interface
Public Class IronPdfService
Implements IPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
End Sub
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte()) Implements IPdfService.GeneratePdfAsync
Using pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Public Async Function GeneratePdfFromUrlAsync(url As String) As Task(Of Byte()) Implements IPdfService.GeneratePdfFromUrlAsync
Using pdf = Await _renderer.RenderUrlAsPdfAsync(url)
Return pdf.BinaryData
End Using
End Function
End Class
Migration du traitement des erreurs
ActivePDF utilise des codes de retour entiers nécessitant des tables de consultation. IronPDF utilise 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}");
}
Dim toolkit As New Toolkit()
Dim result As Integer = toolkit.OpenOutputFile(path)
If result <> 0 Then
' Error - need to look up error code
Console.WriteLine($"Error code: {result}")
End If
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}");
}
Imports IronPdf.Exceptions
Try
Dim renderer = New ChromePdfRenderer()
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(path)
End Using
Catch ex As IronPdfProductException
Console.WriteLine($"IronPDF Error: {ex.Message}")
Catch ex As Exception
Console.WriteLine($"General Error: {ex.Message}")
End Try
Conseils d'optimisation des performances
Réutiliser l'instance du moteur de rendu
La création d'un nouveau ChromePdfRenderer entraîne une surcharge 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");
}
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
For Each html In htmlList
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"output_{i}.pdf")
End Using
Next
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");
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc
Public Class ReportController
Inherits Controller
Public Async Function GenerateReport() As Task(Of IActionResult)
Dim renderer As New ChromePdfRenderer()
Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return File(pdf.BinaryData, "application/pdf")
End Using
End Function
End Class
Élimination correcte des ressources
Utilisez toujours les instructions using pour garantir un nettoyage correct :
using var pdf = renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
using var pdf = renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
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");
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);
' 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)
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
' ActivePDF
toolkit.OpenOutputFile(path)
toolkit.AddHTML(html)
toolkit.CloseOutputFile() ' Required!
' IronPDF - no open/close needed
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(path) ' 'Using' handles cleanup
End Using
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");
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.WaitFor.RenderDelay(2000)
' Or wait for element:
renderer.RenderingOptions.WaitFor.HtmlElementById("content-loaded")
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/");
renderer.RenderingOptions.BaseUrl = New Uri("https://yourdomain.com/assets/")
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èles IronPDF à 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 vers IronPDF modernise 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.

