Passer au contenu du pied de page
VIDéOS

Comment dessiner du texte et des bitmaps sur des PDFs

Apache PDFBox est une bibliothèque Java open source réputée pour la gestion des fichiers PDF. Cependant, pour les développeurs .NET , les options disponibles sont des portages non officiels réalisés par la communauté qui posent des défis importants : des API de type Java, une couverture fonctionnelle incomplète et un soutien limité de la communauté .NET . Ce guide fournit une procédure de migration détaillée depuis les ports .NET d'Apache PDFBox vers IronPDF, une bibliothèque PDF .NET native conçue spécifiquement pour l'écosystème .NET .

Pourquoi envisager une migration depuis les ports .NET d'Apache PDFBox ?

Bien qu'Apache PDFBox soit excellent dans l'écosystème Java, ses portages .NET non officiels présentent plusieurs défis qui affectent les équipes de développement .NET .

Statut de portage officieux

Apache PDFBox est principalement une bibliothèque Java (ligne actuelle 3.0.7, héritage 2.0.36, licence Apache 2.0). Toutes les options .NET sont des ports soutenus par la communauté, et la plupart sont abandonnées : Pdfbox 1.1.1 (dernier publié en 2013, construit contre PDFBox 1.8.2), Pdfbox-IKVM 1.8.9 (dernier publié en mars 2017), et PdfBox_DotNet_Version 2.0.15 (dernier publié en juillet 2019). La seule option activement maintenue est MASES.NetPDF (ligne 3.0.x, suivant PDFBox 3.0.x), qui est un wrapper JCOBridge nécessitant une JVM au moment de l'exécution avec le CLR. Ces ports sont souvent en retard par rapport aux versions Java et peuvent manquer de fonctionnalités critiques, de correctifs ou de mises à jour de sécurité - un risque à peser pour des projets .NET de longue durée.

Conception d'API axée sur Java

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 standard .NET, 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 JVM

Les ports basés sur IKVM (Pdfbox-IKVM, Pdfbox) incluent une réimplémentation .NET de la JVM, tandis que MASES.NetPDF fait appel à une véritable JVM via JCOBridge. Dans tous les cas, le déploiement inclut les contraintes runtime Java que les bibliothèques .NET idiomatiques évitent.

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 Bibliothèque native .NET
Style API Conventions Java (camelCase, close()) C# idiomatique (PascalCase, using)
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
Support Communauté uniquement Support commercial disponible
Nettoyage de ressources Appels explicites close() IDisposable avec des instructions using

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 Package Manager NuGet
  • Clé de licence IronPDF(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 "org.apache.pdfbox\|Org.Apache.Pdfbox\|PDDocument\|PDFTextStripper" --include="*.cs" .
grep -rE "Pdfbox|Pdfbox-IKVM|PdfBox_DotNet_Version|MASES\.NetPDF" --include="*.csproj" .
grep -r "org.apache.pdfbox\|Org.Apache.Pdfbox\|PDDocument\|PDFTextStripper" --include="*.cs" .
grep -rE "Pdfbox|Pdfbox-IKVM|PdfBox_DotNet_Version|MASES\.NetPDF" --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() Instructions using Modifier le mode d'élimination
Accès aux fichiers Objets Java File 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 installez IronPDF:

# Remove whichever PDFBox .NET port your project uses
dotnet remove package Pdfbox            # built against PDFBox 1.8.2 (2013)
dotnet remove package Pdfbox-IKVM       # IKVM wrapper, last update 2017
dotnet remove package PdfBox_DotNet_Version  # last update 2019
dotnet remove package MASES.NetPDF      # JCOBridge wrapper, requires JVM

# Install IronPDF
dotnet add package IronPdf
# Remove whichever PDFBox .NET port your project uses
dotnet remove package Pdfbox            # built against PDFBox 1.8.2 (2013)
dotnet remove package Pdfbox-IKVM       # IKVM wrapper, last update 2017
dotnet remove package PdfBox_DotNet_Version  # last update 2019
dotnet remove package MASES.NetPDF      # JCOBridge wrapper, requires JVM

# Install IronPDF
dotnet add package IronPdf
SHELL

Étape 2 : configuration de la clé de licence

Ajouter la clé de licence IronPDF au démarrage de l'application :

// Add at application startup, before any IronPDF operations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Add at application startup, before any IronPDF operations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
' Add at application startup, before any IronPDF operations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
$vbLabelText   $csharpLabel

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

Effectuez une recherche et un remplacement globaux dans votre solution :

Tous les ports .NET de PDFBox reflètent la hiérarchie des packages Java. Les ports basés sur IKVM conservent la forme en minuscules de Java (org.apache.pdfbox.*); MASES.NetPDF le met en majuscules pour C# (Org.Apache.Pdfbox.*).

Recherche Remplacer par
using org.apache.pdfbox.pdmodel; (ports IKVM) using IronPdf;
using org.apache.pdfbox.text; (ports IKVM) using IronPdf;
using org.apache.pdfbox.multipdf; (ports IKVM) using IronPdf;
using Org.Apache.Pdfbox.Pdmodel; (MASES.NetPDF) using IronPdf;
using Org.Apache.Pdfbox.Text; (MASES.NetPDF) using IronPdf;

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

Opérations documentaires

Méthode Apache PDFBox Méthode IronPDF
PDDocument.load(path) PdfDocument.FromFile(path)
PDDocument.load(stream) PdfDocument.FromStream(stream)
new PDDocument() new ChromePdfRenderer()
document.save(path) pdf.SaveAs(path)
document.close() Instruction using ou Dispose()
document.getNumberOfPages() pdf.PageCount
document.getPage(index) pdf.Pages[index]
document.removePage(index) pdf.RemovePages(index)

Extraction de texte

Méthode Apache PDFBox Méthode IronPDF
new PDFTextStripper() Pas nécessaire
stripper.getText(document) pdf.ExtractAllText()
stripper.setStartPage(n) pdf.Pages[n].Text
stripper.setSortByPosition(true) Automatique

Opérations de fusion et de division

Méthode Apache PDFBox Méthode IronPDF
new PDFMergerUtility() Pas nécessaire
merger.addSource(file) Charger avec FromFile()
merger.mergeDocuments() PdfDocument.Merge(pdfs)
new Splitter() Pas nécessaire
splitter.split(document) pdf.CopyPages(indices)

Sécurité et Chiffrement

Méthode Apache PDFBox Méthode IronPDF
StandardProtectionPolicy pdf.SecuritySettings
policy.setUserPassword() pdf.SecuritySettings.UserPassword
policy.setOwnerPassword() pdf.SecuritySettings.OwnerPassword
policy.setPermissions() pdf.SecuritySettings.AllowUserXxx

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 is a Java library — there is no official .NET port.
// Example uses Pdfbox-IKVM (last published 2017) on NuGet; namespaces
// mirror the Java packages exactly because IKVM exposes the Java API.
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.text;
using java.io;
using System;

class Program
{
    static void Main()
    {
        PDDocument document = PDDocument.load(new File("document.pdf"));
        try
        {
            PDFTextStripper stripper = new PDFTextStripper();
            string text = stripper.getText(document);
            Console.WriteLine(text);
        }
        finally
        {
            document.close();
        }
    }
}
// Apache PDFBox is a Java library — there is no official .NET port.
// Example uses Pdfbox-IKVM (last published 2017) on NuGet; namespaces
// mirror the Java packages exactly because IKVM exposes the Java API.
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.text;
using java.io;
using System;

class Program
{
    static void Main()
    {
        PDDocument document = PDDocument.load(new File("document.pdf"));
        try
        {
            PDFTextStripper stripper = new PDFTextStripper();
            string text = stripper.getText(document);
            Console.WriteLine(text);
        }
        finally
        {
            document.close();
        }
    }
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.text
Imports java.io
Imports System

Module Program
    Sub Main()
        Dim document As PDDocument = PDDocument.load(New File("document.pdf"))
        Try
            Dim stripper As New PDFTextStripper()
            Dim text As String = stripper.getText(document)
            Console.WriteLine(text)
        Finally
            document.close()
        End Try
    End Sub
End Module
$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);
    }
}
Imports IronPdf
Imports System

Class Program
    Shared Sub Main()
        Dim pdf = PdfDocument.FromFile("document.pdf")
        Dim text As String = pdf.ExtractAllText()
        Console.WriteLine(text)

        ' Or extract text from specific pages
        Dim pageText As String = pdf.ExtractTextFromPage(0)
        Console.WriteLine(pageText)
    End Sub
End Class
$vbLabelText   $csharpLabel

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

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.

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");
    }
}
Imports IronPdf
Imports System

Class Program
    Shared Sub Main()
        Dim renderer = New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is HTML to PDF</p>")
        pdf.SaveAs("output.pdf")
        Console.WriteLine("PDF created successfully")
    End Sub
End Class
$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 via a .NET port (e.g. Pdfbox-IKVM on nuget.org).
// The Java class org.apache.pdfbox.multipdf.PDFMergerUtility is exposed
// directly through IKVM, so method names stay Java-style (camelCase).
using org.apache.pdfbox.multipdf;
using org.apache.pdfbox.io;
using System;

class Program
{
    static void Main()
    {
        PDFMergerUtility merger = new PDFMergerUtility();
        merger.addSource("document1.pdf");
        merger.addSource("document2.pdf");
        merger.setDestinationFileName("merged.pdf");
        // MemoryUsageSetting governs heap vs temp-file buffering
        merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        Console.WriteLine("PDFs merged");
    }
}
// Apache PDFBox via a .NET port (e.g. Pdfbox-IKVM on nuget.org).
// The Java class org.apache.pdfbox.multipdf.PDFMergerUtility is exposed
// directly through IKVM, so method names stay Java-style (camelCase).
using org.apache.pdfbox.multipdf;
using org.apache.pdfbox.io;
using System;

class Program
{
    static void Main()
    {
        PDFMergerUtility merger = new PDFMergerUtility();
        merger.addSource("document1.pdf");
        merger.addSource("document2.pdf");
        merger.setDestinationFileName("merged.pdf");
        // MemoryUsageSetting governs heap vs temp-file buffering
        merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        Console.WriteLine("PDFs merged");
    }
}
Imports org.apache.pdfbox.multipdf
Imports org.apache.pdfbox.io
Imports System

Module Program
    Sub Main()
        Dim merger As New PDFMergerUtility()
        merger.addSource("document1.pdf")
        merger.addSource("document2.pdf")
        merger.setDestinationFileName("merged.pdf")
        ' MemoryUsageSetting governs heap vs temp-file buffering
        merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly())
        Console.WriteLine("PDFs merged")
    End Sub
End Module
$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");
    }
}
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 pdf3 = PdfDocument.FromFile("document3.pdf")

        Dim merged = PdfDocument.Merge(pdf1, pdf2, pdf3)
        merged.SaveAs("merged.pdf")
        Console.WriteLine("PDFs merged successfully")
    End Sub
End Module
$vbLabelText   $csharpLabel

La méthode statique Merge d'IronPDF accepte directement plusieurs documents, éliminant le modèle de 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();
    }
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.pdmodel.font
Imports org.apache.pdfbox.pdmodel.edit

Public Sub CreatePdf(outputPath As String)
    Dim document As New PDDocument()
    Try
        Dim page As New PDPage()
        document.addPage(page)

        Dim contentStream As New PDPageContentStream(document, page)
        Dim font As PDFont = 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()
    End Try
End Sub
$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);
}
Imports IronPdf

Public Sub CreatePdf(outputPath As String)
    Dim renderer As New ChromePdfRenderer()

    Dim html As String = "
        <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 pdf = renderer.RenderHtmlAsPdf(html)
        pdf.SaveAs(outputPath)
    End Using
End Sub
$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();
    }
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.pdmodel.encryption

Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
    Dim document As PDDocument = PDDocument.load(New File(inputPath))
    Try
        Dim ap As New AccessPermission()
        ap.setCanPrint(True)
        ap.setCanExtractContent(False)

        Dim spp As New StandardProtectionPolicy(password, password, ap)
        spp.setEncryptionKeyLength(128)

        document.protect(spp)
        document.save(outputPath)
    Finally
        document.close()
    End Try
End Sub
$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);
}
Imports IronPdf

Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
    Using pdf = PdfDocument.FromFile(inputPath)
        pdf.SecuritySettings.UserPassword = password
        pdf.SecuritySettings.OwnerPassword = password
        pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
        pdf.SecuritySettings.AllowUserCopyPasteContent = False

        pdf.SaveAs(outputPath)
    End Using
End Sub
$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();
    }
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.pdmodel.edit
Imports org.apache.pdfbox.pdmodel.font

Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
    Dim document As PDDocument = PDDocument.load(New File(inputPath))
    Try
        Dim font As PDFont = PDType1Font.HELVETICA_BOLD

        For i As Integer = 0 To document.getNumberOfPages() - 1
            Dim page As PDPage = document.getPage(i)
            Dim cs As 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()
        Next

        document.save(outputPath)
    Finally
        document.close()
    End Try
End Sub
$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);
}
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
$vbLabelText   $csharpLabel

Le filigrane HTML d'IronPDF élimine l'itération de page et les calculs matriciels.

Conversion d'URL en PDF

Apache PDFBox ne prend pas en charge la conversion d'URL en PDF.IronPDF assure 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);
}
Imports IronPdf

Public Sub ConvertUrlToPdf(url As String, outputPath As String)
    Dim renderer As New ChromePdfRenderer()
    Using pdf = renderer.RenderUrlAsPdf(url)
        pdf.SaveAs(outputPath)
    End Using
End Sub
$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.IronPDF offre 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);
}
Imports IronPdf

Public Sub CreatePdfWithHeaderFooter(html As String, outputPath As String)
    Dim renderer = New ChromePdfRenderer()

    renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
        .CenterText = "Document Title",
        .FontSize = 12
    }

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

    Using pdf = renderer.RenderHtmlAsPdf(html)
        pdf.SaveAs(outputPath)
    End Using
End Sub
$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");
}
<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
$vbLabelText   $csharpLabel

Support asynchrone

Les ports Apache PDFBox ne supportent pas les opérations asynchrones.IronPDF offre 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;
}
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
$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();
    }
}
Imports System.Threading.Tasks

Public Interface IPdfService
    Function GeneratePdfAsync(html As String) As Task(Of Byte())
    Function ExtractText(pdfPath As String) As String
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 Function ExtractText(pdfPath As String) As String Implements IPdfService.ExtractText
        Using pdf = PdfDocument.FromFile(pdfPath)
            Return pdf.ExtractAllText()
        End Using
    End Function
End Class
$vbLabelText   $csharpLabel

Optimisation des performances

Comparaison de l'utilisation de la mémoire

Scénario Apache PDFBox .NET Port IronPDF
Extraction de texte ~80 MB ~50 MB
Création de PDF ~100 MB ~60 MB
Lot (100 PDF) Élevé (nettoyage manuel) ~100 MB

Conseils d'optimisation

Utilisez des instructions using :

// Automatiquecleanup with IDisposable pattern
using var pdf = PdfDocument.FromFile(path);
// Automatiquecleanup with IDisposable pattern
using var pdf = PdfDocument.FromFile(path);
Imports PdfDocument

' Automatic cleanup with IDisposable pattern
Using pdf = PdfDocument.FromFile(path)
    ' Your code here
End Using
$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");
}
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
$vbLabelText   $csharpLabel

Utiliser Async dans les applications Web:

using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
$vbLabelText   $csharpLabel

Dépannage des problèmes de migration courants

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

Remplacez les méthodes Java camelCase par les é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
' PDFBox: stripper.getText(document)
' IronPDF: pdf.ExtractAllText()

' PDFBox: document.getNumberOfPages()
' IronPDF: pdf.PageCount
$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
' PDFBox
document.Close()

' IronPDF
Using pdf = PdfDocument.FromFile(path)
    ' Automatic disposal at end of scope
End Using
$vbLabelText   $csharpLabel

Problème : Pas d'équivalent 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;
' IronPDF: Just call ExtractAllText()
Dim text As String = pdf.ExtractAllText()

' Per-page extraction:
Dim pageText As String = pdf.Pages(0).Text
$vbLabelText   $csharpLabel

Problème : PDFMergerUtility introuvable

Utilisez la méthode statique Merge :

//IronPDF uses static Merge
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
//IronPDF uses static Merge
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
'IronPDF uses static Merge
Dim merged = PdfDocument.Merge(pdf1, pdf2, pdf3)
$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 la précision de l'extraction de texte
  • Vérifiez que la licence fonctionne correctement (IronPdf.License.IsLicensed)
  • Évaluation comparative des performances par rapport à l'implémentation précédente
  • Mettre à jour les dépendances du pipeline CI/CD
  • Documentez les nouveaux modèles pour votre équipe de développement

Ressources supplémentaires


La migration des ports Apache PDFBox .NET vers IronPDF transforme 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.

Veuillez noterApache PDFBox est une marque déposée de son propriétaire respectif. Ce site n'est pas affilié, approuvé ou sponsorisé par la Fondation Apache Software. Tous les noms de produits, logos et marques sont la propriété de leurs propriétaires respectifs. Les comparaisons sont à titre informatif uniquement et reflètent les informations publiquement disponibles au moment de l'écriture.

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

Équipe de soutien Iron

Nous sommes en ligne 24 heures sur 24, 5 jours sur 7.
Chat
Email
Appelez-moi