Passer au contenu du pied de page
GUIDES DE MIGRATION

Comment migrer d'Apache PDFBox vers IronPDF

Migrer d'Apache PDFBox versIronPDF: Guide complet de migration en C

Apache PDFBox est une bibliothèque Java open-source très respectée pour la manipulation des PDF. Cependant, pour les développeurs .NET, les seules options disponibles sont les ports non officiels gérés par la communauté, qui posent des problèmes importants : API de type Java, couverture incomplète des fonctionnalités et faible soutien de la communauté .NET. Ce guide complet fournit un chemin de migration étape par étape des ports Apache PDFBox .NET vers IronPDF, une bibliothèque PDF native .NET conçue dès le départ pour l'écosystème .NET.

Pourquoi abandonner les ports .NET d'Apache PDFBox?

Si Apache PDFBox excelle dans l'écosystème Java, ses ports .NET non officiels posent plusieurs problèmes aux équipes de développement .NET.

Statut de portage officieux

Apache PDFBox est fondamentalement une bibliothèque Java. Toutes les versions de .NET sont des ports communautaires qui ne bénéficient pas du soutien officiel du projet Apache. Ces ports sont souvent en retard sur les versions Java et peuvent manquer des fonctionnalités critiques, des corrections de bogues ou des mises à jour de sécurité. Pour les équipes qui conçoivent des applications dont les exigences de longévité s'étendent jusqu'en 2025 et 2026, cette incertitude crée un risque technique.

Java-First API Design

Les API portées conservent les conventions Java qui semblent étrangères au code .NET. Les développeurs rencontrent des méthodes camelCase au lieu de PascalCase, des objets Java File au lieu de chaînes .NET standard, et des appels explicites close() au lieu de motifs IDisposable. Cette surcharge cognitive affecte la vitesse de développement et la maintenabilité du code.

Aucune capacité de rendu HTML

Apache PDFBox est conçu pour la manipulation de PDF, et non pour la conversion de HTML en PDF. La création de PDF nécessite une construction manuelle des pages avec un positionnement précis des coordonnées - un processus fastidieux et sujet aux erreurs qui n'est pas adapté aux besoins modernes de génération de documents.

Support limité de la communauté .NET

L'écosystème .NET autour des ports Apache PDFBox est peu développé. Il est difficile de trouver de l'aide, des exemples ou des bonnes pratiques pour les questions spécifiques à .NET par rapport aux bibliothèques disposant d'une communauté .NET active.

Dépendances potentielles de la JVM

Certains ports d'Apache PDFBox peuvent nécessiter des composants d'exécution Java, ce qui complexifie le déploiement et la gestion de l'environnement dans une infrastructure axée sur .NET.

Apache PDFBox vs.IronPDF: Principales différences

Comprendre les différences fondamentales entre ces bibliothèques permet de planifier une stratégie de migration efficace.

Aspect Ports .NET d'Apache PDFBox IronPDF
Native Design Portage .NET non officiel, centré sur Java Native .NET, prise en charge professionnelle
Style API Conventions Java (camelCase, close()) C# idiomatique (PascalCase, utilisant)
Rendu HTML Non pris en charge (construction manuelle de la page) HTML/CSS/JS complet basé sur Chromium
Création de PDF Positionnement manuel des coordonnées Mise en page basée sur les CSS
Communauté Ressources axées sur Java, peu de ressources .NET Communauté .NET active, plus de 10 millions de téléchargements
Support Communauté uniquement Support professionnel disponible
Nettoyage de ressources Appels explicites de close() IDisposable with using statements

Préparation de la migration

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)

Audit de l'utilisation d'Apache PDFBox

Exécutez ces commandes dans le répertoire de votre solution pour identifier toutes les références à Apache PDFBox :

grep -r "apache.pdfbox\|PdfBox\|PDDocument\|PDFTextStripper" --include="*.cs" .
grep -r "PdfBox\|Apache.PdfBox" --include="*.csproj" .
grep -r "apache.pdfbox\|PdfBox\|PDDocument\|PDFTextStripper" --include="*.cs" .
grep -r "PdfBox\|Apache.PdfBox" --include="*.csproj" .
SHELL

Modifications importantes à prévoir

Catégorie Apache PDFBox .NET Port IronPDF Action de migration
Modèle d'objet PDDocument, PDPage PdfDocument, ChromePdfRenderer Hiérarchie de classe différente
Création de PDF Flux manuels de pages/contenus Rendu HTML Réécriture de la logique de création
Style de la méthode camelCase() (style Java) PascalCase() (style .NET) Mise à jour des noms de méthodes
Nettoyage des ressources document.close() utiliser les déclarations Modifier le mode d'élimination
Accès aux fichiers Objets File de Java Chaînes/flux .NET Standard Utiliser les types .NET
Extraction de texte classe PDFTextStripper pdf.ExtractAllText() API plus simple

Processus de migration étape par étape

Étape 1 : Mise à jour des paquets NuGet

Supprimez les paquets du port .NET d'Apache PDFBox et installezIronPDF:

# Remove PDFBox .NET port packages
dotnet remove package PdfBox
dotnet remove package PDFBoxNet
dotnet remove package Apache.PdfBox

# Install IronPDF
dotnet add package IronPdf
# Remove PDFBox .NET port packages
dotnet remove package PdfBox
dotnet remove package PDFBoxNet
dotnet remove package Apache.PdfBox

# Install IronPDF
dotnet add package IronPdf
SHELL

Étape 2 : configuration de la clé de licence

Ajouter la clé de licenceIronPDFau démarrage de l'application :

// Add at application startup, before anyIronPDFoperations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Add at application startup, before anyIronPDFoperations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 org.apache.pdfbox.pdmodel; utiliser IronPdf;
utilisant org.apache.pdfbox.text; utiliser IronPdf;
utilisant org.apache.pdfbox.multipdf; utiliser IronPdf;
utilisant PdfBoxDotNet.Pdmodel; utiliser IronPdf;
utilisant Apache.Pdfbox.PdModel; utiliser IronPdf;

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

Opérations documentaires

Méthode Apache PDFBox Méthode IronPDF Notes
PDDocument.load(path) PdfDocument.FromFile(path) Charger le PDF
PDDocument.load(stream) PdfDocument.FromStream(stream) Charger à partir du flux
new PDDocument() new ChromePdfRenderer() Pour la création de PDF
document.save(path) pdf.SaveAs(path) Sauvegarder le PDF
document.close() utilisant l'instruction ou Dispose() Nettoyage
document.getNumberOfPages() pdf.PageCount Propriété du nombre de pages
document.getPage(index) pdf.Pages[index] Page d'accès
document.removePage(index) pdf.RemovePages(index) Supprimer des pages

Extraction de texte

Méthode Apache PDFBox Méthode IronPDF Notes
new PDFTextStripper() Pas nécessaire Aucun objet à découper n'est nécessaire
stripper.getText(document) pdf.ExtractAllText() Extraction complète de documents
stripper.setStartPage(n) pdf.Pages[n].Text Extraction par page
stripper.setSortByPosition(true) Automatique Tri de texte intégré

Opérations de fusion et de division

Méthode Apache PDFBox Méthode IronPDF Notes
new PDFMergerUtility() Pas nécessaire Méthode de fusion statique
merger.addSource(file) Charger avec FromFile() Chargez d'abord les documents
merger.mergeDocuments() PdfDocument.Merge(pdfs) Fusion statique
new Splitter() Pas nécessaire Manipulation directe des pages
splitter.split(document) pdf.CopyPages(indices) Copier des pages spécifiques

Sécurité et Chiffrement

Méthode Apache PDFBox Méthode IronPDF Notes
Politique de protection standard pdf.SecuritySettings Configuration de la sécurité
policy.setUserPassword() pdf.SecuritySettings.UserPassword Mot de passe utilisateur
policy.setOwnerPassword() pdf.SecuritySettings.OwnerPassword Mot de passe du propriétaire
policy.setPermissions() pdf.SecuritySettings.AllowUserXxx Autorisations

Exemples de migration de code

Extraction de texte

L'opération la plus courante d'Apache PDFBox démontre la simplification de l'API qu'IronPDF apporte.

Mise en œuvre du portage d'Apache PDFBox .NET:

// Apache PDFBox .NET ports are experimental and incomplete
using PdfBoxDotNet.Pdmodel;
using PdfBoxDotNet.Text;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Note: PDFBox-dotnet has limited functionality
        using (var document = PDDocument.Load("document.pdf"))
        {
            var stripper = new PDFTextStripper();
            string text = stripper.GetText(document);
            Console.WriteLine(text);
        }
    }
}
// Apache PDFBox .NET ports are experimental and incomplete
using PdfBoxDotNet.Pdmodel;
using PdfBoxDotNet.Text;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Note: PDFBox-dotnet has limited functionality
        using (var document = PDDocument.Load("document.pdf"))
        {
            var stripper = new PDFTextStripper();
            string text = stripper.GetText(document);
            Console.WriteLine(text);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

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

class Program
{
    static void Main()
    {
        var pdf = PdfDocument.FromFile("document.pdf");
        string text = pdf.ExtractAllText();
        Console.WriteLine(text);

        // Or extract text from specific pages
        string pageText = pdf.ExtractTextFromPage(0);
        Console.WriteLine(pageText);
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        var pdf = PdfDocument.FromFile("document.pdf");
        string text = pdf.ExtractAllText();
        Console.WriteLine(text);

        // Or extract text from specific pages
        string pageText = pdf.ExtractTextFromPage(0);
        Console.WriteLine(pageText);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF élimine entièrement la classe PDFTextStripper, remplaçant l'extraction en plusieurs étapes par un appel de méthode unique.

Conversion HTML en PDF

Apache PDFBox ne prend pas en charge la conversion HTML-PDF en mode natif, ce qui représente une lacune fondamentale.

Apache PDFBox .NET Port (non pris en charge):

// Apache PDFBox does not have official .NET port
// Community ports like PDFBox-dotnet are incomplete
// and do not support HTML to PDF conversion natively.
// You would need to use additional libraries like
// iText or combine with HTML renderers separately.

using PdfBoxDotNet.Pdmodel;
using System.IO;

// Note: This is NOT supported in PDFBox
// PDFBox is primarily for PDF manipulation, not HTML rendering
// You would need external Rendu HTMLengine
// Apache PDFBox does not have official .NET port
// Community ports like PDFBox-dotnet are incomplete
// and do not support HTML to PDF conversion natively.
// You would need to use additional libraries like
// iText or combine with HTML renderers separately.

using PdfBoxDotNet.Pdmodel;
using System.IO;

// Note: This is NOT supported in PDFBox
// PDFBox is primarily for PDF manipulation, not HTML rendering
// You would need external Rendu HTMLengine
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

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

class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is HTML to PDF</p>");
        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.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is HTML to PDF</p>");
        pdf.SaveAs("output.pdf");
        Console.WriteLine("PDF created successfully");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Le moteur de rendu d'IronPDF, basé sur Chromium, offre une prise en charge complète de HTML, CSS et JavaScript. Pour les scénarios avancés, consultez la documentation HTML vers PDF.

Fusionner plusieurs fichiers PDF

Mise en œuvre du portage d'Apache PDFBox .NET:

// Apache PDFBox .NET port attempt (incomplete support)
using PdfBoxDotNet.Pdmodel;
using PdfBoxDotNet.Multipdf;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // PDFBox-dotnet ports have incomplete API coverage
        var merger = new PDFMergerUtility();
        merger.AddSource("document1.pdf");
        merger.AddSource("document2.pdf");
        merger.SetDestinationFileName("merged.pdf");
        merger.MergeDocuments();
        Console.WriteLine("PDFs merged");
    }
}
// Apache PDFBox .NET port attempt (incomplete support)
using PdfBoxDotNet.Pdmodel;
using PdfBoxDotNet.Multipdf;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // PDFBox-dotnet ports have incomplete API coverage
        var merger = new PDFMergerUtility();
        merger.AddSource("document1.pdf");
        merger.AddSource("document2.pdf");
        merger.SetDestinationFileName("merged.pdf");
        merger.MergeDocuments();
        Console.WriteLine("PDFs merged");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

// NuGet: Install-Package 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 pdf3 = PdfDocument.FromFile("document3.pdf");

        var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
        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("document1.pdf");
        var pdf2 = PdfDocument.FromFile("document2.pdf");
        var pdf3 = PdfDocument.FromFile("document3.pdf");

        var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
        merged.SaveAs("merged.pdf");
        Console.WriteLine("PDFs merged successfully");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

La méthode statique Merge d'IronPDF accepte directement plusieurs documents, éliminant ainsi le modèle de la classe utilitaire.

Créer des PDF à partir de rien

La différence la plus spectaculaire apparaît lors de la création de PDF. Apache PDFBox nécessite un positionnement manuel des coordonnées.

Mise en œuvre du portage d'Apache PDFBox .NET:

using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.font;
using org.apache.pdfbox.pdmodel.edit;

public void CreatePdf(string outputPath)
{
    PDDocument document = new PDDocument();
    try
    {
        PDPage page = new PDPage();
        document.addPage(page);

        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        PDFont font = PDType1Font.HELVETICA_BOLD;

        contentStream.beginText();
        contentStream.setFont(font, 24);
        contentStream.moveTextPositionByAmount(72, 700);
        contentStream.drawString("Hello World");
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(PDType1Font.HELVETICA, 12);
        contentStream.moveTextPositionByAmount(72, 650);
        contentStream.drawString("This is a paragraph of text.");
        contentStream.endText();

        contentStream.close();
        document.save(outputPath);
    }
    finally
    {
        document.close();
    }
}
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.font;
using org.apache.pdfbox.pdmodel.edit;

public void CreatePdf(string outputPath)
{
    PDDocument document = new PDDocument();
    try
    {
        PDPage page = new PDPage();
        document.addPage(page);

        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        PDFont font = PDType1Font.HELVETICA_BOLD;

        contentStream.beginText();
        contentStream.setFont(font, 24);
        contentStream.moveTextPositionByAmount(72, 700);
        contentStream.drawString("Hello World");
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(PDType1Font.HELVETICA, 12);
        contentStream.moveTextPositionByAmount(72, 650);
        contentStream.drawString("This is a paragraph of text.");
        contentStream.endText();

        contentStream.close();
        document.save(outputPath);
    }
    finally
    {
        document.close();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Mise en œuvre d'IronPDF:

using IronPdf;

public void CreatePdf(string outputPath)
{
    var renderer = new ChromePdfRenderer();

    string html = @"
        <html>
        <head>
            <style>
                body { font-family: Helvetica, Arial, sans-serif; margin: 1in; }
                h1 { font-size: 24pt; font-weight: bold; }
                p { font-size: 12pt; }
            </style>
        </head>
        <body>
            <h1>Hello World</h1>
            <p>This is a paragraph of text.</p>
        </body>
        </html>";

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

public void CreatePdf(string outputPath)
{
    var renderer = new ChromePdfRenderer();

    string html = @"
        <html>
        <head>
            <style>
                body { font-family: Helvetica, Arial, sans-serif; margin: 1in; }
                h1 { font-size: 24pt; font-weight: bold; }
                p { font-size: 12pt; }
            </style>
        </head>
        <body>
            <h1>Hello World</h1>
            <p>This is a paragraph of text.</p>
        </body>
        </html>";

    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(outputPath);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

La création basée sur HTML/CSS élimine les calculs de coordonnées, la gestion des polices et la manipulation des flux de contenu.

Ajouter une protection par mot de passe

Mise en œuvre du portage d'Apache PDFBox .NET:

using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.encryption;

public void ProtectPdf(string inputPath, string outputPath, string password)
{
    PDDocument document = PDDocument.load(new File(inputPath));
    try
    {
        AccessPermission ap = new AccessPermission();
        ap.setCanPrint(true);
        ap.setCanExtractContent(false);

        StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
        spp.setEncryptionKeyLength(128);

        document.protect(spp);
        document.save(outputPath);
    }
    finally
    {
        document.close();
    }
}
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.encryption;

public void ProtectPdf(string inputPath, string outputPath, string password)
{
    PDDocument document = PDDocument.load(new File(inputPath));
    try
    {
        AccessPermission ap = new AccessPermission();
        ap.setCanPrint(true);
        ap.setCanExtractContent(false);

        StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
        spp.setEncryptionKeyLength(128);

        document.protect(spp);
        document.save(outputPath);
    }
    finally
    {
        document.close();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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.UserPassword = password;
    pdf.SecuritySettings.OwnerPassword = password;
    pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
    pdf.SecuritySettings.AllowUserCopyPasteContent = false;

    pdf.SaveAs(outputPath);
}
using IronPdf;

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

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

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

IronPDF utilise des propriétés fortement typées au lieu d'objets de permission et de politique distincts.

Ajouter des filigranes

Mise en œuvre du portage d'Apache PDFBox .NET:

using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.edit;
using org.apache.pdfbox.pdmodel.font;

public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
    PDDocument document = PDDocument.load(new File(inputPath));
    try
    {
        PDFont font = PDType1Font.HELVETICA_BOLD;

        for (int i = 0; i < document.getNumberOfPages(); i++)
        {
            PDPage page = document.getPage(i);
            PDPageContentStream cs = new PDPageContentStream(
                document, page, PDPageContentStream.AppendMode.APPEND, true, true);

            cs.beginText();
            cs.setFont(font, 72);
            cs.setNonStrokingColor(200, 200, 200);
            cs.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(45), 200, 400));
            cs.showText(watermarkText);
            cs.endText();
            cs.close();
        }

        document.save(outputPath);
    }
    finally
    {
        document.close();
    }
}
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.edit;
using org.apache.pdfbox.pdmodel.font;

public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
    PDDocument document = PDDocument.load(new File(inputPath));
    try
    {
        PDFont font = PDType1Font.HELVETICA_BOLD;

        for (int i = 0; i < document.getNumberOfPages(); i++)
        {
            PDPage page = document.getPage(i);
            PDPageContentStream cs = new PDPageContentStream(
                document, page, PDPageContentStream.AppendMode.APPEND, true, true);

            cs.beginText();
            cs.setFont(font, 72);
            cs.setNonStrokingColor(200, 200, 200);
            cs.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(45), 200, 400));
            cs.showText(watermarkText);
            cs.endText();
            cs.close();
        }

        document.save(outputPath);
    }
    finally
    {
        document.close();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Le filigrane basé sur le HTML d'IronPDF élimine l'itération des pages et les calculs de matrice.

Conversion d'URL en PDF

Apache PDFBox ne prend pas en charge la conversion d'URL en PDF.IronPDFassure la prise en charge native :

using IronPdf;

public void ConvertUrlToPdf(string url, string outputPath)
{
    var renderer = new ChromePdfRenderer();
    using var pdf = renderer.RenderUrlAsPdf(url);
    pdf.SaveAs(outputPath);
}
using IronPdf;

public void ConvertUrlToPdf(string url, string outputPath)
{
    var renderer = new ChromePdfRenderer();
    using var pdf = renderer.RenderUrlAsPdf(url);
    pdf.SaveAs(outputPath);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Pour connaître l'ensemble des options de conversion d'URL, consultez la documentation sur les URL au format PDF.

En-têtes et pieds de page

Apache PDFBox nécessite un positionnement manuel sur chaque page, sans prise en charge intégrée des en-têtes/pieds de page.IronPDFoffre une configuration déclarative :

using IronPdf;

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

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

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

    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 = "Document Title",
        FontSize = 12
    };

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

    using var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(outputPath);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Pour les mises en page avancées, voir la documentation sur les en-têtes et les pieds de page.

Intégration d'ASP.NET Core

IronPDF s'intègre naturellement aux applications web .NET modernes :

[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");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Support asynchrone

Les ports Apache PDFBox ne supportent pas les opérations asynchrones.IronPDFoffre des fonctionnalités complètes d'asynchronisme et d'attente :

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;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Configuration de l'injection de dépendance

public interface IPdfService
{
    Task<byte[]> GeneratePdfAsync(string html);
    string ExtractText(string pdfPath);
}

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 string ExtractText(string pdfPath)
    {
        using var pdf = PdfDocument.FromFile(pdfPath);
        return pdf.ExtractAllText();
    }
}
public interface IPdfService
{
    Task<byte[]> GeneratePdfAsync(string html);
    string ExtractText(string pdfPath);
}

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 string ExtractText(string pdfPath)
    {
        using var pdf = PdfDocument.FromFile(pdfPath);
        return pdf.ExtractAllText();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Optimisation des performances

Comparaison de l'utilisation de la mémoire

Scénario Apache PDFBox .NET Port IronPDF Notes
Extraction de texte ~80 MB ~50 MB IronPDFplus efficace
Création de PDF ~100 MB ~60 MB Rendu HTML optimisé
Lot (100 PDF) Élevé (nettoyage manuel) ~100 MB Utiliser les déclarations utilisant

Conseils d'optimisation

Utiliser les déclarations utilisant:

// Automatiquecleanup with IDisposable pattern
using var pdf = PdfDocument.FromFile(path);
// Automatiquecleanup with IDisposable pattern
using var pdf = PdfDocument.FromFile(path);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Réutiliser le rendu pour les opérations par lots :

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");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Utiliser Async dans les applications Web:

using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Dépannage des problèmes de migration courants

Problème : Noms de méthodes de type Java introuvables

Remplacer les méthodes Java camelCase par des équivalents .NET PascalCase :

// PDFBox: stripper.getText(document)
// IronPDF: pdf.ExtractAllText()

// PDFBox: document.getNumberOfPages()
// IronPDF: pdf.PageCount
// PDFBox: stripper.getText(document)
// IronPDF: pdf.ExtractAllText()

// PDFBox: document.getNumberOfPages()
// IronPDF: pdf.PageCount
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Problème : Pas de méthode close()

IronPDF utilise le modèle IDisposable :

// PDFBox
document.close();

// IronPDF
using var pdf = PdfDocument.FromFile(path);
// Automatiquedisposal at end of scope
// PDFBox
document.close();

// IronPDF
using var pdf = PdfDocument.FromFile(path);
// Automatiquedisposal at end of scope
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Problème : Pas d'équivalent de PDFTextStripper

L'extraction de texte est simplifiée à une seule méthode :

// IronPDF: Just call ExtractAllText()
string text = pdf.ExtractAllText();

// Per-page extraction:
string pageText = pdf.Pages[0].Text;
// IronPDF: Just call ExtractAllText()
string text = pdf.ExtractAllText();

// Per-page extraction:
string pageText = pdf.Pages[0].Text;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Enjeu : PDFMergerUtility introuvable

Utilisez la méthode statique Merge :

//IronPDFuses static Merge
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
//IronPDFuses static Merge
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 sorties PDF avec les versions précédentes
  • [Tester la précision de l'extraction de texte
  • [Vérifier que la licence fonctionne correctement (IronPdf.License.IsLicensed)
  • [La traduction doit rester professionnelle, en préservant la précision technique tout en expliquant les caractéristiques et les avantages de ces outils de développement
  • [Mise à jour des dépendances du pipeline CI/CD
  • [Documenter de nouveaux modèles pour votre équipe de développement

Protéger l'avenir de votre infrastructure PDF

Avec .NET 10 à l'horizon et C# 14 introduisant de nouvelles fonctionnalités de langage, le choix d'une bibliothèque PDF .NET native garantit la compatibilité 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 les projets s'étendent jusqu'en 2025 et 2026.

Ressources supplémentaires


La migration des ports Apache PDFBox .NET versIronPDFtransforme votre base de code PDF, qui passe de modèles de style Java à un langage C# idiomatique. Le passage du positionnement manuel des coordonnées au rendu HTML/CSS, combiné à la prise en charge asynchrone native et à l'intégration .NET moderne, permet d'obtenir un code plus propre et plus facile à maintenir, avec un support professionnel soutenant vos applications de production.

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