Passer au contenu du pied de page
VIDéOS

Comment convertir HTML en PDF dans une vue ASP.NET MVC

Migrer de PDFsharp à IronPDF transforme votre flux de travail de génération de PDF, passant du dessin manuel basé sur les coordonnées à la modélisation HTML/CSS moderne. Ce guide fournit un chemin de migration étape par étape qui remplace le positionnement de style GDI+ par des technologies web, réduisant le temps de développement et rendant la génération de PDF maintenable à travers des compétences standard HTML/CSS.

Pourquoi migrer de PDFsharp à IronPDF

Comprendre PDFsharp

PDFsharp est une bibliothèque de création de PDF de bas niveau qui permet aux développeurs de générer des documents PDF de manière programmatique. Publié sous licence MIT et maintenu par le PDFsharp-Team (initialement empira Software GmbH), PDFsharp 6.x cible .NET 8/9/10 et .NET Standard 2.0 et fonctionne de manière multiplateforme sur Windows, Linux et macOS via la version Core. PDFsharp fonctionne principalement comme un outil pour dessiner et compiler des PDFs à partir de zéro en utilisant une API de style GDI+, ce qui peut être à la fois bénéfique et restrictif selon la nature du projet.

PDFsharp est parfois à tort supposé être un convertisseur HTML en PDF, ce qu'il n'est pas. L'objectif est uniquement la création programmatique de documents PDF. Bien qu'il existe un addon communautaire, HtmlRenderer.PdfSharp (par ArthurHub), destiné à fournir des capacités de rendu HTML, il couvre uniquement HTML 4.01 / CSS niveau 2 - pas de fonctionnalités CSS modernes comme flexbox, grille, ou JavaScript.

Le problème du calcul des coordonnées

L'approche en GDI+ de PDFsharp signifie que vous devez :

  • Calculer les positions X,Y exactes de chaque élément
  • Suivi manuel de la hauteur du contenu pour le débordement de la page
  • Gérez vous-même le retour à la ligne et la mesure du texte
  • Dessiner des tableaux cellule par cellule avec des calculs de bordures
  • Gérer des documents de plusieurs pages avec des sauts de page manuels

L'architecture de PDFsharp nécessite une compréhension approfondie du positionnement en utilisant des coordonnées, posant souvent des défis dans la création de mises en page complexes.

Comparaison PDFsharp vs IronPDF

Fonction PDFsharp IronPDF
Licence MIT (gratuit) Commercial
Support HTML vers PDF Non Oui (prise en charge de HTML5/CSS3)
Support CSS moderne Non (HTML 4.01/CSS 2 via add-on HtmlRenderer) Oui (CSS3 complet)
Création de documents Dessin à base de coordonnées Modèles HTML/CSS
Système de mise en page Positionnement manuel X,Y CSS Flow/Flexbox/Grid
Sauts de page Calcul manuel Automatique + contrôle CSS
Tables Dessiner des cellules individuellement HTML <table>
Styling Polices/couleurs basées sur le code Feuilles de style CSS
Document API Bas niveau (nécessite des coordonnées) Haut niveau (API simplifiée)
Mises à jour Actif (ligne 6.x) Régulièrement

IronPDF brille dans les scénarios où les documents HTML doivent être convertis en PDF avec une fidélité totale. Cette bibliothèque .NET prend en charge HTML5 et CSS3, ce qui garantit le respect des normes web modernes. Grâce à ses capacités natives de conversion de HTML en PDF, les développeurs peuvent tirer parti du contenu web existant ou des modèles conçus avec des outils web contemporains.

Pour les équipes sur .NET moderne, IronPDF fournit une approche qui élimine les calculs de coordonnées tout en tirant parti des compétences en développement web.


Avant de commencer

Prérequis

  1. Environnement .NET : .NET Framework 4.6.2+ ou .NET Core 3.1+ / .NET 5/6/7/8/9+
  2. Accès à NuGet : possibilité d'installer des packages NuGet
  3. Licence IronPDF : Obtenez votre clé de licence sur IronPDF

Modifications du paquet NuGet

# Remove PDFsharp (official PDFsharp-Team package IDs; case-sensitive on case-sensitive feeds)
dotnet remove package PDFsharp
# dotnet remove package PDFsharp-WPF        # if you used the WPF build
# dotnet remove package PDFsharp-GDI        # if you used the GDI build
# dotnet remove package PDFsharp-MigraDoc   # if you used MigraDoc on top
# dotnet remove package PdfSharpCore        # community .NET Standard port

# Add IronPDF
dotnet add package IronPdf
# Remove PDFsharp (official PDFsharp-Team package IDs; case-sensitive on case-sensitive feeds)
dotnet remove package PDFsharp
# dotnet remove package PDFsharp-WPF        # if you used the WPF build
# dotnet remove package PDFsharp-GDI        # if you used the GDI build
# dotnet remove package PDFsharp-MigraDoc   # if you used MigraDoc on top
# dotnet remove package PdfSharpCore        # community .NET Standard port

# Add IronPDF
dotnet add package IronPdf
SHELL

Configuration de la licence

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

Identifier l'utilisation de PDFsharp

# Find all PDFsharp usages in your codebase
grep -r "PdfSharp\|XGraphics\|XFont\|XBrush\|XPen" --include="*.cs" .
# Find all PDFsharp usages in your codebase
grep -r "PdfSharp\|XGraphics\|XFont\|XBrush\|XPen" --include="*.cs" .
SHELL

Référence API complète

Modifications de l'espace de nommage

// Before: PDFsharp
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Pdf.IO;

// After: IronPDF
using IronPdf;
using IronPdf.Editing;
// Before: PDFsharp
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Pdf.IO;

// After: IronPDF
using IronPdf;
using IronPdf.Editing;
Imports IronPdf
Imports IronPdf.Editing
$vbLabelText   $csharpLabel

Mappages de l'API de base

API PDFsharp API IronPDF
new PdfDocument() ChromePdfRenderer.RenderHtmlAsPdf()
document.AddPage() Automatique
XGraphics.FromPdfPage() Pas nécessaire
XGraphics.DrawString() HTML <p>, <h1>, etc.
XGraphics.DrawImage() HTML <img> tag
XFont CSS font-family, font-size
XBrush, XPen Couleurs/bordures CSS
document.Save() pdf.SaveAs()
PdfReader.Open() PdfDocument.FromFile()

Exemples de migration de code

Exemple 1 : Conversion HTML vers PDF

Avant (PDFsharp) :

// NuGet: Install-Package PDFsharp (official PDFsharp-Team package, MIT)
// PDFsharp does NOT support HTML-to-PDF natively. The community add-on
// HtmlRenderer.PdfSharp covers HTML 4.01 / CSS level 2 only (no flexbox, grid, JS).
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // PDFsharp does not have built-in HTML vers PDF conversion
        // You need to manually parse HTML and render content
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XFont font = new XFont("Arial", 12);

        // Manuel text rendering (no HTML support)
        gfx.DrawString("Hello from PDFsharp", font, XBrushes.Black,
            new XRect(0, 0, page.Width, page.Height),
            XStringFormats.TopLeft);

        document.Save("output.pdf");
    }
}
// NuGet: Install-Package PDFsharp (official PDFsharp-Team package, MIT)
// PDFsharp does NOT support HTML-to-PDF natively. The community add-on
// HtmlRenderer.PdfSharp covers HTML 4.01 / CSS level 2 only (no flexbox, grid, JS).
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // PDFsharp does not have built-in HTML vers PDF conversion
        // You need to manually parse HTML and render content
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XFont font = new XFont("Arial", 12);

        // Manuel text rendering (no HTML support)
        gfx.DrawString("Hello from PDFsharp", font, XBrushes.Black,
            new XRect(0, 0, page.Width, page.Height),
            XStringFormats.TopLeft);

        document.Save("output.pdf");
    }
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports System

Class Program
    Shared Sub Main()
        ' PDFsharp does not have built-in HTML vers PDF conversion
        ' You need to manually parse HTML and render content
        Dim document As New PdfDocument()
        Dim page As PdfPage = document.AddPage()
        Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
        Dim font As New XFont("Arial", 12)

        ' Manuel text rendering (no HTML support)
        gfx.DrawString("Hello from PDFsharp", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.TopLeft)

        document.Save("output.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

Après (IronPDF):

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

class Program
{
    static void Main()
    {
        // IronPDF has native HTML vers PDF rendering
        var renderer = new ChromePdfRenderer();

        string html = "<h1>Hello from IronPDF</h1><p>Easy HTML vers PDF conversion</p>";
        var pdf = renderer.RenderHtmlAsPdf(html);

        pdf.SaveAs("output.pdf");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        // IronPDF has native HTML vers PDF rendering
        var renderer = new ChromePdfRenderer();

        string html = "<h1>Hello from IronPDF</h1><p>Easy HTML vers PDF conversion</p>";
        var pdf = renderer.RenderHtmlAsPdf(html);

        pdf.SaveAs("output.pdf");
    }
}
Imports IronPdf
Imports System

Class Program
    Shared Sub Main()
        ' IronPDF has native HTML vers PDF rendering
        Dim renderer As New ChromePdfRenderer()

        Dim html As String = "<h1>Hello from IronPDF</h1><p>Easy HTML vers PDF conversion</p>"
        Dim pdf = renderer.RenderHtmlAsPdf(html)

        pdf.SaveAs("output.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

Cet exemple met en évidence la différence la plus importante entre les deux bibliothèques. PDFsharp ne propose pas de conversion HTML en PDF intégrée — vous devez créer manuellement un PdfDocument, ajouter un PdfPage, obtenir un objet XGraphics, créer un XFont, et utiliser DrawString() avec des coordonnées XRect.

IronPDF offre un rendu HTML en PDF natif via ChromePdfRenderer. La méthode RenderHtmlAsPdf() accepte des chaînes HTML et les convertit en utilisant un moteur Chromium en interne. IronPDF convertit facilement les fichiers HTML en PDF, en préservant tous les styles définis en HTML5 et CSS3, éliminant ainsi le besoin de calculs de coordonnées. Consultez la documentation HTML vers PDF pour des exemples complets.

Exemple 2 : Ajout d'un texte ou d'un filigrane à un PDF existant

Avant (PDFsharp) :

// NuGet: Install-Package PDFsharp (official PDFsharp-Team package, MIT)
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // Open existing PDF
        PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify);
        PdfPage page = document.Pages[0];

        // Get graphics object
        XGraphics gfx = XGraphics.FromPdfPage(page);
        // Note: in PDFsharp 6.x, XFontStyle was renamed to XFontStyleEx
        XFont font = new XFont("Arial", 20, XFontStyleEx.Bold);

        // Draw text at specific position
        gfx.DrawString("Watermark Text", font, XBrushes.Red,
            new XPoint(200, 400));

        document.Save("modified.pdf");
    }
}
// NuGet: Install-Package PDFsharp (official PDFsharp-Team package, MIT)
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // Open existing PDF
        PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify);
        PdfPage page = document.Pages[0];

        // Get graphics object
        XGraphics gfx = XGraphics.FromPdfPage(page);
        // Note: in PDFsharp 6.x, XFontStyle was renamed to XFontStyleEx
        XFont font = new XFont("Arial", 20, XFontStyleEx.Bold);

        // Draw text at specific position
        gfx.DrawString("Watermark Text", font, XBrushes.Red,
            new XPoint(200, 400));

        document.Save("modified.pdf");
    }
}
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports PdfSharp.Drawing
Imports System

Module Program
    Sub Main()
        ' Open existing PDF
        Dim document As PdfDocument = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify)
        Dim page As PdfPage = document.Pages(0)

        ' Get graphics object
        Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
        ' Note: in PDFsharp 6.x, XFontStyle was renamed to XFontStyleEx
        Dim font As XFont = New XFont("Arial", 20, XFontStyleEx.Bold)

        ' Draw text at specific position
        gfx.DrawString("Watermark Text", font, XBrushes.Red, New XPoint(200, 400))

        document.Save("modified.pdf")
    End Sub
End Module
$vbLabelText   $csharpLabel

Après (IronPDF):

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

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

        // Open existing PDF
        var pdf = PdfDocument.FromFile("existing.pdf");

        // Add text stamp/watermark
        var textStamper = new TextStamper()
        {
            Text = "Watermark Text",
            FontSize = 20,
            FontFamily = "Arial",
            IsBold = true,
            FontColor = IronSoftware.Drawing.Color.Red,
            VerticalAlignment = VerticalAlignment.Middle,
            HorizontalAlignment = HorizontalAlignment.Center
        };

        pdf.ApplyStamp(textStamper);
        pdf.SaveAs("modified.pdf");
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using IronPdf.Editing;
using System;

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

        // Open existing PDF
        var pdf = PdfDocument.FromFile("existing.pdf");

        // Add text stamp/watermark
        var textStamper = new TextStamper()
        {
            Text = "Watermark Text",
            FontSize = 20,
            FontFamily = "Arial",
            IsBold = true,
            FontColor = IronSoftware.Drawing.Color.Red,
            VerticalAlignment = VerticalAlignment.Middle,
            HorizontalAlignment = HorizontalAlignment.Center
        };

        pdf.ApplyStamp(textStamper);
        pdf.SaveAs("modified.pdf");
    }
}
Imports IronPdf
Imports IronPdf.Editing
Imports System

Module Program
    Sub Main()
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"

        ' Open existing PDF
        Dim pdf = PdfDocument.FromFile("existing.pdf")

        ' Add text stamp/watermark
        Dim textStamper = New TextStamper() With {
            .Text = "Watermark Text",
            .FontSize = 20,
            .FontFamily = "Arial",
            .IsBold = True,
            .FontColor = IronSoftware.Drawing.Color.Red,
            .VerticalAlignment = VerticalAlignment.Middle,
            .HorizontalAlignment = HorizontalAlignment.Center
        }

        pdf.ApplyStamp(textStamper)
        pdf.SaveAs("modified.pdf")
    End Sub
End Module
$vbLabelText   $csharpLabel

PDFsharp nécessite l'ouverture du PDF avec PdfReader.Open() en spécifiant PdfDocumentOpenMode.Modify, accédant à une page, créer un objet XGraphics, créer un XFont avec style, et utiliser DrawString() avec un XPoint spécifiant des coordonnées X,Y exactes (200, 400).

IronPDF simplifie cela avec PdfDocument.FromFile(), un objet TextStamper avec des propriétés déclaratives (Text, FontSize, FontFamily, IsBold, FontColor, VerticalAlignment, HorizontalAlignment), et ApplyStamp(). Aucun calcul de coordonnées n'est nécessaire : il suffit de spécifier l'alignement et IronPDF se charge du positionnement. Notez que le namespace IronPdf.Editing est requis pour la fonction de tamponnage.

Exemple 3 : Création de PDF avec des images

Avant (PDFsharp) :

// NuGet: Install-Package PDFsharp (official PDFsharp-Team package, MIT)
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // Create new PDF document
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);

        // Load and draw image
        XImage image = XImage.FromFile("image.jpg");

        // Calculate size to fit page
        double width = 200;
        double height = 200;

        gfx.DrawImage(image, 50, 50, width, height);

        // Add text
        XFont font = new XFont("Arial", 16);
        gfx.DrawString("Image in PDF", font, XBrushes.Black,
            new XPoint(50, 270));

        document.Save("output.pdf");
    }
}
// NuGet: Install-Package PDFsharp (official PDFsharp-Team package, MIT)
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System;

class Program
{
    static void Main()
    {
        // Create new PDF document
        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        XGraphics gfx = XGraphics.FromPdfPage(page);

        // Load and draw image
        XImage image = XImage.FromFile("image.jpg");

        // Calculate size to fit page
        double width = 200;
        double height = 200;

        gfx.DrawImage(image, 50, 50, width, height);

        // Add text
        XFont font = new XFont("Arial", 16);
        gfx.DrawString("Image in PDF", font, XBrushes.Black,
            new XPoint(50, 270));

        document.Save("output.pdf");
    }
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports System

Class Program
    Shared Sub Main()
        ' Create new PDF document
        Dim document As New PdfDocument()
        Dim page As PdfPage = document.AddPage()
        Dim gfx As XGraphics = XGraphics.FromPdfPage(page)

        ' Load and draw image
        Dim image As XImage = XImage.FromFile("image.jpg")

        ' Calculate size to fit page
        Dim width As Double = 200
        Dim height As Double = 200

        gfx.DrawImage(image, 50, 50, width, height)

        ' Add text
        Dim font As New XFont("Arial", 16)
        gfx.DrawString("Image in PDF", font, XBrushes.Black, New XPoint(50, 270))

        document.Save("output.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

Après (IronPDF):

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

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

        // Create PDF from HTML with image
        var renderer = new ChromePdfRenderer();

        string html = @"
            <h1>Image in PDF</h1>
            <img src='image.jpg' style='width:200px; height:200px;' />
            <p>Easy image embedding with HTML</p>";

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

        // Alternative: Add image to existing PDF
        var existingPdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Document</h1>");
        var imageStamper = new IronPdf.Editing.ImageStamper(new Uri("image.jpg"))
        {
            VerticalAlignment = IronPdf.Editing.VerticalAlignment.Top
        };
        existingPdf.ApplyStamp(imageStamper);
    }
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

        // Create PDF from HTML with image
        var renderer = new ChromePdfRenderer();

        string html = @"
            <h1>Image in PDF</h1>
            <img src='image.jpg' style='width:200px; height:200px;' />
            <p>Easy image embedding with HTML</p>";

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

        // Alternative: Add image to existing PDF
        var existingPdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Document</h1>");
        var imageStamper = new IronPdf.Editing.ImageStamper(new Uri("image.jpg"))
        {
            VerticalAlignment = IronPdf.Editing.VerticalAlignment.Top
        };
        existingPdf.ApplyStamp(imageStamper);
    }
}
Imports IronPdf
Imports System

Module Program
    Sub Main()
        IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"

        ' Create PDF from HTML with image
        Dim renderer As New ChromePdfRenderer()

        Dim html As String = "
            <h1>Image in PDF</h1>
            <img src='image.jpg' style='width:200px; height:200px;' />
            <p>Easy image embedding with HTML</p>"

        Dim pdf = renderer.RenderHtmlAsPdf(html)
        pdf.SaveAs("output.pdf")

        ' Alternative: Add image to existing PDF
        Dim existingPdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Document</h1>")
        Dim imageStamper = New IronPdf.Editing.ImageStamper(New Uri("image.jpg")) With {
            .VerticalAlignment = IronPdf.Editing.VerticalAlignment.Top
        }
        existingPdf.ApplyStamp(imageStamper)
    End Sub
End Module
$vbLabelText   $csharpLabel

PDFsharp nécessite de créer un nouveau PdfDocument, ajouter un PdfPage, obtenir XGraphics, charger un XImage à partir du fichier, calculer la largeur et la hauteur, utiliser DrawImage() avec des coordonnées exactes (50, 50, 200, 200), puis ajouter séparément du texte avec DrawString().

IronPDF utilise le HTML standard avec une balise <img> et du style CSS (style='width:200px; height:200px;&#39;). Aucun calcul de coordonnées n'est nécessaire - la mise en page est gérée par CSS. IronPDF propose également ImageStamper pour ajouter des images aux PDFs existants avec des propriétés d'alignement déclaratives. Pour en savoir plus, consultez nos tutoriels.


Notes de migration essentielles

Changement de paradigme : Les coordonnées vers HTML/CSS

Le changement le plus important est le passage du dessin basé sur les coordonnées à HTML/CSS :

// PDFsharp: manual positioning
gfx.DrawString("Invoice", titleFont, XBrushes.Black, new XPoint(50, 50));
gfx.DrawString("Customer: John", bodyFont, XBrushes.Black, new XPoint(50, 80));

// IronPDF: let CSS handle layout
var html = @"
<div style='padding: 50px;'>
    <h1>Invoice</h1>
    <p>Customer: John</p>
</div>";
var pdf = renderer.RenderHtmlAsPdf(html);
// PDFsharp: manual positioning
gfx.DrawString("Invoice", titleFont, XBrushes.Black, new XPoint(50, 50));
gfx.DrawString("Customer: John", bodyFont, XBrushes.Black, new XPoint(50, 80));

// IronPDF: let CSS handle layout
var html = @"
<div style='padding: 50px;'>
    <h1>Invoice</h1>
    <p>Customer: John</p>
</div>";
var pdf = renderer.RenderHtmlAsPdf(html);
Imports PdfSharp.Drawing
Imports IronPdf

' PDFsharp: manual positioning
gfx.DrawString("Invoice", titleFont, XBrushes.Black, New XPoint(50, 50))
gfx.DrawString("Customer: John", bodyFont, XBrushes.Black, New XPoint(50, 80))

' IronPDF: let CSS handle layout
Dim html As String = "
<div style='padding: 50px;'>
    <h1>Invoice</h1>
    <p>Customer: John</p>
</div>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
$vbLabelText   $csharpLabel

Migration des polices

// PDFsharp: XFont objects (PDFsharp 6.x renamed XFontStyle to XFontStyleEx)
var titleFont = new XFont("Arial", 24, XFontStyleEx.Bold);
var bodyFont = new XFont("Times New Roman", 12);

// IronPDF: CSS font properties
var html = @"
<style>
    h1 { font-family: Arial, sans-serif; font-size: 24px; font-weight: bold; }
    p { font-family: 'Times New Roman', serif; font-size: 12px; }
</style>";
// PDFsharp: XFont objects (PDFsharp 6.x renamed XFontStyle to XFontStyleEx)
var titleFont = new XFont("Arial", 24, XFontStyleEx.Bold);
var bodyFont = new XFont("Times New Roman", 12);

// IronPDF: CSS font properties
var html = @"
<style>
    h1 { font-family: Arial, sans-serif; font-size: 24px; font-weight: bold; }
    p { font-family: 'Times New Roman', serif; font-size: 12px; }
</style>";
' PDFsharp: XFont objects (PDFsharp 6.x renamed XFontStyle to XFontStyleEx)
Dim titleFont As New XFont("Arial", 24, XFontStyleEx.Bold)
Dim bodyFont As New XFont("Times New Roman", 12)

' IronPDF: CSS font properties
Dim html As String = "
<style>
    h1 { font-family: Arial, sans-serif; font-size: 24px; font-weight: bold; }
    p { font-family: 'Times New Roman', serif; font-size: 12px; }
</style>"
$vbLabelText   $csharpLabel

Changement de chargement de document

// PDFsharp: PdfReader.Open()
PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify);

// IronPDF: PdfDocument.FromFile()
var pdf = PdfDocument.FromFile("existing.pdf");
// PDFsharp: PdfReader.Open()
PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify);

// IronPDF: PdfDocument.FromFile()
var pdf = PdfDocument.FromFile("existing.pdf");
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports IronPdf

' PDFsharp: PdfReader.Open()
Dim document As PdfDocument = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify)

' IronPDF: PdfDocument.FromFile()
Dim pdf As PdfDocument = PdfDocument.FromFile("existing.pdf")
$vbLabelText   $csharpLabel

Enregistrer le changement de méthode

// PDFsharp: document.Save()
document.Save("output.pdf");

// IronPDF: pdf.SaveAs()
pdf.SaveAs("output.pdf");
// PDFsharp: document.Save()
document.Save("output.pdf");

// IronPDF: pdf.SaveAs()
pdf.SaveAs("output.pdf");
' PDFsharp: document.Save()
document.Save("output.pdf")

' IronPDF: pdf.SaveAs()
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

Modification de l'accès à la page

// PDFsharp: document.Pages[0]
PdfPage page = document.Pages[0];

// IronPDF: Automatique page handling or pdf.Pages[0]
// Pages are created automatically from HTML content
// PDFsharp: document.Pages[0]
PdfPage page = document.Pages[0];

// IronPDF: Automatique page handling or pdf.Pages[0]
// Pages are created automatically from HTML content
' PDFsharp: document.Pages(0)
Dim page As PdfPage = document.Pages(0)

' IronPDF: Automatique page handling or pdf.Pages(0)
' Pages are created automatically from HTML content
$vbLabelText   $csharpLabel

Nouvelles capacités après la migration

Après avoir migré vers IronPDF, vous acquérez des capacités que PDFsharp ne peut pas fournir :

HTML natif vers PDF

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Modern Web Content</h1>");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Modern Web Content</h1>");
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Modern Web Content</h1>")
$vbLabelText   $csharpLabel

URL en PDF

var pdf = renderer.RenderUrlAsPdf("https://example.com");
var pdf = renderer.RenderUrlAsPdf("https://example.com");
Dim pdf = renderer.RenderUrlAsPdf("https://example.com")
$vbLabelText   $csharpLabel

Fusion de fichiers PDF

var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2);
var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2);
Dim pdf1 = PdfDocument.FromFile("document1.pdf")
Dim pdf2 = PdfDocument.FromFile("document2.pdf")
Dim merged = PdfDocument.Merge(pdf1, pdf2)
$vbLabelText   $csharpLabel

Les filigranes avec HTML

pdf.ApplyWatermark("<h2 style='color:red;'>CONFIDENTIAL</h2>");
pdf.ApplyWatermark("<h2 style='color:red;'>CONFIDENTIAL</h2>");
pdf.ApplyWatermark("<h2 style='color:red;'>CONFIDENTIAL</h2>")
$vbLabelText   $csharpLabel

Résumé de la comparaison des fonctionnalités

Fonction PDFsharp IronPDF
Dessin à base de coordonnées ✗(utiliser HTML)
HTML vers PDF
Prise en charge CSS3
Mise en page Flexbox/grille
Estampillage de texte Manuel XGraphics TextStamper
Estampillage d'images Manuel XImage ImageStamper
Fusionner des PDF Manuel
URL vers PDF
Rendu Web moderne Moteur Chromium
Sauts de page automatiques

Liste de contrôle de la migration

Pré-migration

  • Inventoriez toute utilisation de PDFsharp dans le codebase
  • Identifier les types de documents générés (rapports, factures, certificats)
  • Notez toute opération graphique ou de dessin personnalisée
  • Planifier le stockage de la clé de licence IronPDF (variables d'environnement recommandées)
  • Commencez par tester avec une licence d'essai IronPDF.

Modifications du paquet

  • Supprimer le package NuGet PDFsharp (package officiel de l'équipe PDFsharp)
  • Supprimer PDFsharp-WPF, PDFsharp-GDI, ou PDFsharp-MigraDoc si utilisés
  • Supprimer PdfSharpCore si vous utilisiez le port communauté .NET Standard
  • Installer le package NuGet IronPdf: dotnet add package IronPdf

Modifications du code

  • Mettre à jour les imports de namespaces (using PdfSharp.Pdf;using IronPdf;)
  • Ajouter using IronPdf.Editing; pour la fonction de tamponnage
  • Convertir les mises en page basées sur des coordonnées en HTML/CSS
  • Remplacer XFont par des propriétés de police CSS
  • Remplacer XPen par des couleurs/bordures CSS
  • Remplacer XGraphics.DrawString() par des éléments de texte HTML
  • Remplacer XGraphics.DrawImage() par des balises HTML <img>
  • Remplacer PdfReader.Open() par PdfDocument.FromFile()
  • Remplacer document.Save() par pdf.SaveAs()
  • Convertir le code de dessin de tableau en tableaux HTML

Après la migration

  • Comparaison visuelle des PDF générés
  • Testez les documents de plusieurs pages
  • Vérifier le rendu des polices
  • Ajouter de nouvelles fonctionnalités (HTML vers PDF, fusion, filigranes) selon les besoins

Veuillez noterPDFsharp est une marque déposée de son propriétaire respectif. Ce site n'est pas affilié, approuvé ou parrainé par PDFsharp-Team ou empira Software GmbH. 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