Passer au contenu du pied de page
COMPARAISONS DE PRODUITS

IronPDF vs ABCpdf : Quelle Bibliothèque PDF C# Offre la Meilleure Conversion HTML en PDF en 2025 ?

Les fichiers PDF sont utilisés dans divers secteurs pour des tâches telles que la facturation et la génération de différents types de documents. Ils permettent de répondre efficacement aux exigences des clients. Lors de la création d'applications .NET nécessitant la génération de PDF, le choix de la bonne bibliothèque peut avoir un impact significatif sur la vitesse de développement, la qualité des résultats et les coûts de maintenance à long terme. Deux bibliothèques fréquemment considérées par les développeurs sont IronPDF et ABCpdf - mais laquelle fournit vraiment de meilleurs résultats pour vos besoins spécifiques ?

Cette comparaison complète examine les capacités des deux bibliothèques, de la précision de la conversion HTML-PDF aux modèles de licence, afin de vous aider à prendre une décision éclairée. Nous explorerons les mesures de performance réelles, la philosophie de conception des API et les exemples de code pratiques qui démontrent les forces et les limites de chaque bibliothèque. Que vous construisiez une plateforme SaaS qui génère des milliers de factures par jour ou une application d'entreprise nécessitant un rendu de document au pixel près, la compréhension de ces différences est cruciale pour la réussite du projet.

Qu'est-ce qu'IronPDF?

IronPDF est une bibliothèque de génération de PDF de qualité commerciale qui aide les ingénieurs logiciels C# à éditer, extraire et générer des documents PDF dans des projets .NET. Construit avec un moteur de rendu basé sur Chrome à son cœur, IronPDF transforme HTML, CSS et JavaScript en PDF avec la même fidélité que celle que vous attendez de l'impression d'une page web dans Google Chrome.

Caractéristiques principales d'IronPDF

IronPDF utilise un moteur .NET Chromium pour rendre les pages HTML en fichiers PDF. Avec HTML-to-PDF, il n'est pas nécessaire d'utiliser des API complexes pour positionner ou concevoir des PDF. IronPDF prend en charge les documents web standard : HTML, ASPX, JS, CSS et images. L'architecture de la bibliothèque privilégie l'expérience du développeur tout en maintenant une qualité de production de niveau professionnel.

Excellence de la conversion HTML vers PDF

  • Prise en charge complète du HTML, y compris des éléments sémantiques HTML5
  • Prise en charge complète de CSS3, y compris Flexbox, Grid et les techniques de mise en page modernes
  • Exécution JavaScript pour le rendu de contenu dynamique
  • Prise en charge des polices Web, y compris Google Fonts et les déclarations @font-face personnalisées
  • Rendu responsive design avec contrôle du viewport
  • Chargement de contenu AJAX avec temps d'attente configurable

Capacités de manipulation de documents

  • Fusionner et diviser : Combinez plusieurs PDF ou extrayez des pages spécifiques à l'aide d'appels de méthode uniques
  • <En-têtes et pieds de page : Ajoutez du contenu dynamique, notamment des numéros de page, des dates et du code HTML personnalisé
  • Watermarking : Appliquez des filigranes de texte ou d'image avec contrôle de l'opacité et du positionnement
  • Gestion des formulaires : Créer automatiquement des formulaires PDF remplissables à partir d'éléments de formulaires HTML
  • Signatures numériques : Appliquer des signatures cryptographiques avec la gestion des certificats
  • Cryptage : mise en œuvre du cryptage AES 128 bits et 256 bits avec des autorisations granulaires

Fonctionnalités de rendu avancées

  • Traitement multithread : prise en charge native de l'asynchronisme et de l'attente pour des scénarios à hautes performances
  • Opérations par lots : Méthodes optimisées pour le traitement simultané de plusieurs documents
  • Efficacité de la mémoire : prise en charge de la diffusion en continu pour la génération de documents volumineux sans charger des PDF entiers en mémoire
  • Optimisation du cloud : Conçu pour les déploiements conteneurisés dans Docker, Azure et AWS

Architecture multiplateforme

IronPDF maintient un comportement cohérent dans différents environnements :

  • Windows (x86/x64)
  • Linux (y compris Alpine pour les images Docker minimales)
  • macOS (Intel et Apple Silicon)
  • Azure App Service, Functions et Container Instances
  • AWS Lambda et EC2
  • Plate-forme Google Cloud

Qu'est-ce qu'ABCpdf?

La bibliothèque PDF C# ABCpdf .NET est un composant .NET pour la lecture dynamique, l'écriture, la conversion et la manipulation de documents Adobe PDF. Développé par WebSupergoo, ABCpdf est au service de la communauté .NET depuis plus de vingt ans, offrant de multiples moteurs de rendu HTML et des fonctionnalités complètes de manipulation de PDF.

Caractéristiques principales d'ABCpdf

ABCpdf supporte entièrement HTML/CSS et les technologies connexes telles que JavaScript, SVG, AJAX et Font Awesome. La bibliothèque fournit aux développeurs des méthodes de commodité de haut niveau et un accès de bas niveau aux objets PDF.

Moteurs de rendu multiples

L'approche unique d'ABCpdf offre plusieurs moteurs de rendu :

  • ABCChrome Engine : basé sur Chromium pour des standards web modernes (x64 seulement)
  • <Moteur Gecko : Plusieurs versions pour les tests de compatibilité
  • MSHTML Engine : rendu basé sur Internet Explorer
  • <Moteur ABCWebKit : Rendu basé sur WebKit (x64 uniquement)

Cette approche multi-moteurs permet aux développeurs de choisir le meilleur moteur de rendu pour leur contenu spécifique, bien qu'elle ajoute de la complexité au déploiement et aux tests.

Capacités d'importation de documents

ABCpdf peut lire une variété de formats de documents lorsque des applications d'aide comme OpenOffice.org sont installées. Les formats pris en charge sont les suivants :

  • Documents Microsoft Office (Word, Excel, PowerPoint)
  • Fichiers PostScript et EPS
  • XPS (XML Paper Specification)
  • SVG (Scalable Vector Graphics)
  • Différents formats d'image, notamment les formats TIFF, JPEG 2000 et RAW

Manipulation PDF de bas niveau

  • Accès direct au modèle d'objet PDF
  • Compression/décompression de flux avec plusieurs algorithmes
  • Contrôle du sous-ensemble et de l'intégration des polices
  • Gestion et conversion de l'espace couleur
  • Manipulation de flux de contenu

Caractéristiques de performance

ABCpdf est entièrement multithread, ce qui lui permet d'être utilisé de manière flexible dans divers environnements .NET, y compris C#, ASPX et VB, et il a été testé dans des environnements multithread haute performance. La bibliothèque comprend :

  • Prise en charge de GigaPDF™ pour les documents extrêmement volumineux
  • Utilisation optimisée de la mémoire pour les environnements de serveurs
  • Mécanismes efficaces de mise en cache des polices
  • Capacités de traitement des threads en arrière-plan

Prise en charge des cadres CSS modernes

Lorsque l'on travaille avec des applications web contemporaines, la capacité à convertir au format PDF des mises en page basées sur Bootstrap et d'autres frameworks CSS modernes est de plus en plus essentielle. De nombreuses applications d'entreprise et plateformes SaaS s'appuient désormais sur Bootstrap pour la cohérence de leur interface utilisateur, et la génération de PDF doit préserver parfaitement ces mises en page.

IronPDF : Prise en charge complète de Bootstrap et des cadres modernes

Le moteur de rendu Chromium d'IronPDF offre une prise en charge complète des cadres CSS modernes :

  • Bootstrap 5 : Prise en charge complète des mises en page basées sur la méthode flexbox, des systèmes de grille et des utilitaires réactifs
  • Bootstrap 4 : Compatibilité totale avec les jeux de cartes, les barres de navigation et les mises en page de formulaires flexbox
  • Tailwind CSS : Un cadre CSS moderne, axé sur l'utilité, qui offre un rendu parfait
  • Fondation : Tous les systèmes de grille et de composants sont pris en charge
  • CSS3 moderne : Flexbox, CSS Grid, animations, transitions et propriétés personnalisées

Real-world examples: Bootstrap homepage and Bootstrap templates convert to PDF with pixel-perfect accuracy.

Exemple de code : Grille de produits pour le commerce électronique

using IronPdf;

var renderer = new ChromePdfRenderer();

string bootstrapProductGrid = @"
<!DOCTYPE html>
<html>
<head>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
    <div class='container my-5'>
        <h1 class='mb-4'>Product Catalog</h1>
        <div class='row row-cols-1 row-cols-md-3 g-4'>
            <div class='col'>
                <div class='card h-100'>
                    <img src='https://via.placeholder.com/300x200' class='card-img-top' alt='Product 1'>
                    <div class='card-body d-flex flex-column'>
                        <h5 class='card-title'>Premium Widget</h5>
                        <p class='card-text flex-grow-1'>High-quality widget with advanced features and excellent durability.</p>
                        <div class='d-flex justify-content-between align-items-center mt-auto'>
                            <span class='h4 mb-0 text-primary'>$99.99</span>
                            <button class='btn btn-primary'>Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class='col'>
                <div class='card h-100'>
                    <img src='https://via.placeholder.com/300x200' class='card-img-top' alt='Product 2'>
                    <div class='card-body d-flex flex-column'>
                        <h5 class='card-title'>Standard Widget</h5>
                        <p class='card-text flex-grow-1'>Reliable widget perfect for everyday use with great value.</p>
                        <div class='d-flex justify-content-between align-items-center mt-auto'>
                            <span class='h4 mb-0 text-primary'>$49.99</span>
                            <button class='btn btn-primary'>Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class='col'>
                <div class='card h-100'>
                    <img src='https://via.placeholder.com/300x200' class='card-img-top' alt='Product 3'>
                    <div class='card-body d-flex flex-column'>
                        <h5 class='card-title'>Basic Widget</h5>
                        <p class='card-text flex-grow-1'>Entry-level widget with essential features at an affordable price.</p>
                        <div class='d-flex justify-content-between align-items-center mt-auto'>
                            <span class='h4 mb-0 text-primary'>$29.99</span>
                            <button class='btn btn-primary'>Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(bootstrapProductGrid);
pdf.SaveAs("product-catalog.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

string bootstrapProductGrid = @"
<!DOCTYPE html>
<html>
<head>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
</head>
<body>
    <div class='container my-5'>
        <h1 class='mb-4'>Product Catalog</h1>
        <div class='row row-cols-1 row-cols-md-3 g-4'>
            <div class='col'>
                <div class='card h-100'>
                    <img src='https://via.placeholder.com/300x200' class='card-img-top' alt='Product 1'>
                    <div class='card-body d-flex flex-column'>
                        <h5 class='card-title'>Premium Widget</h5>
                        <p class='card-text flex-grow-1'>High-quality widget with advanced features and excellent durability.</p>
                        <div class='d-flex justify-content-between align-items-center mt-auto'>
                            <span class='h4 mb-0 text-primary'>$99.99</span>
                            <button class='btn btn-primary'>Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class='col'>
                <div class='card h-100'>
                    <img src='https://via.placeholder.com/300x200' class='card-img-top' alt='Product 2'>
                    <div class='card-body d-flex flex-column'>
                        <h5 class='card-title'>Standard Widget</h5>
                        <p class='card-text flex-grow-1'>Reliable widget perfect for everyday use with great value.</p>
                        <div class='d-flex justify-content-between align-items-center mt-auto'>
                            <span class='h4 mb-0 text-primary'>$49.99</span>
                            <button class='btn btn-primary'>Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class='col'>
                <div class='card h-100'>
                    <img src='https://via.placeholder.com/300x200' class='card-img-top' alt='Product 3'>
                    <div class='card-body d-flex flex-column'>
                        <h5 class='card-title'>Basic Widget</h5>
                        <p class='card-text flex-grow-1'>Entry-level widget with essential features at an affordable price.</p>
                        <div class='d-flex justify-content-between align-items-center mt-auto'>
                            <span class='h4 mb-0 text-primary'>$29.99</span>
                            <button class='btn btn-primary'>Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(bootstrapProductGrid);
pdf.SaveAs("product-catalog.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Sortie : Un catalogue de produits parfaitement formaté avec le système de grille de Bootstrap 5, l'alignement flexbox et l'espacement réactif, le tout conservé dans le PDF.

ABCpdf : Approche multi-moteurs avec les limites du framework

La prise en charge par ABCpdf des cadres CSS modernes varie considérablement en fonction du moteur de rendu que vous sélectionnez :

  • ABCChrome Engine (x64 uniquement) : Bonne prise en charge de Bootstrap similaire à IronPDF, mais nécessite une configuration spécifique de la plateforme 64 bits
  • <Moteur ABCWebKit (x64 uniquement) : Prise en charge limitée de flexbox, les mises en page Bootstrap 4+ peuvent ne pas s'afficher correctement
  • Moteur Gecko : Support CSS3 modéré, Bootstrap 3 fonctionne mieux que Bootstrap 4/5
  • Moteur MSHTML : Rendu hérité d'Internet Explorer, Bootstrap 2.x uniquement, non recommandé pour les applications modernes

<Considérations clés :

  • La complexité de la sélection des moteurs alourdit le déploiement
  • les moteurs 64 bits uniquement (ABCChrome, ABCWebKit) limitent la flexibilité du déploiement
  • Tests requis sur tous les moteurs pour un rendu Bootstrap cohérent
  • La compatibilité des frameworks varie considérablement en fonction du choix du moteur

L'architecture multi-moteurs d'ABCpdf offre une grande flexibilité, mais nécessite une sélection minutieuse des moteurs et des tests pour s'assurer que les mises en page Bootstrap s'affichent correctement. Pour les applications fortement investies dans Bootstrap ou les frameworks CSS modernes, le moteur ABCChrome fournit les meilleurs résultats mais s'accompagne de contraintes de déploiement sur x64 uniquement.

Pour plus de détails sur la compatibilité du cadre Bootstrap, voir le Bootstrap & Flexbox CSS Guide.

Comparaison complète des fonctionnalités

Table 4
Comparaison des caractéristiques d'IronPDF et d'ABCpdf pour les applications .NET
Windows primaire, Linux limité
Catégorie Fonctionnalité/Aspect IronPDF Art> Abcpdf Abcpdf Abcpdf Tableau ABCpdf Avantage clé
Architecture de base Philosophie de conception Simplicité d'abord, API intuitives Flexibilité d'abord, plusieurs moteurs IronPDF : Développement plus rapide
Complexité de l'API Méthodes simples comme RenderHtmlAsPdf() Objectif avec la classe Doc IronPDF : 70% de code en moins
Courbe d'apprentissage 1-2 heures typique 1-2 jours typique IronPDF : Adoption plus rapide
Support de plateforme Toutes plates-formes confondues Support natif, paquetage unique Windows primaire, paquetage unique IronPDF : Véritablement multiplateforme
Versions .NET .NET 10, 9, 8, 7, 6, 5, Core 3.1+, Framework 4.6.2+ .NET 10, 9, 8, 7, 6, 5, 4.0, Framework 2.0+ Les deux : prise en charge des cadres modernes
Systèmes d'exploitation Windows, Linux, macOS, Docker natif Windows, support Linux limité IronPDF : Prise en charge plus large des systèmes d'exploitation
HTML vers PDF Moteur de rendu Moteur Chrome V127+ Moteurs multiples (Chrome 123, Gecko, MSHTML) ABCpdf : Flexibilité du moteur
CSS3/HTML5 Support Compatibilité Chrome à 100% Variable selon le moteur (70-100%) IronPDF : Rendu cohérent
Exécution JavaScript Support complet de JavaScript V8 Dépendant du moteur IronPDF : Fonctionnalités JS modernes
Polices Web Google Fonts, @font-face, polices système Supporté par ABCChrome Les deux : prise en charge des polices Web
Performance Rendu d'une seule page 200-400ms typique 150-300ms (ABCChrome) ABCpdf : Légèrement plus rapide
Traitement par lots Traitement parallèle optimisé Capacité multithread IronPDF : Meilleur support asynchrone
Utilisation de la mémoire 150-200MB (moteur Chrome) 100-150MB (varie selon le moteur) ABCpdf : Empreinte mémoire plus faible
Expérience du développeur Documentation Tutoriels, vidéos, exemples détaillés Documentation complète sur les API IronPDF : Plus de ressources d'apprentissage
Exemples de code 100+ échantillons prêts à l'emploi Exemples étendus Les deux : Exemples riches
Support d'IntelliSense Documentation complète en XML IntelliSense complet Les deux : intégration IDE
Licence et prix Niveau d'entrée Lite : $799 (1 dev, 1 projet) Standard : $329 (1 dev, 32-bit only) ABCpdf : Coût d'entrée plus faible
Professionnel Professionnel : $2,399 (10 devs, 10 projects) Professionnel : $479 (1 dev, 64-bit) IronPDF : Meilleure licence pour l'équipe
Redistribution +$2,399 libre de droits $4,790 Licence d'entreprise IronPDF : Plus abordable
Support Support inclus Oui, support technique 24/5 Oui, support par email Oui, support technique 24/5 Oui, support par email IronPDF : Assistance par chat en direct
Délai de réponse < 1 minute (chat en direct) 24-48 heures typique IronPDF : Réponse plus rapide
Parfait pour Cas d'utilisation Applications web modernes, SaaS, cloud-native Windows desktop, systèmes hérités En fonction du contexte
Note. ABCpdf offre plusieurs moteurs de rendu pour plus de flexibilité mais nécessite Windows pour une fonctionnalité complète. IronPDF offre des performances multiplateformes constantes avec le dernier moteur Chrome. Les structures de prix diffèrent considérablement entre les licences pour développeur unique et les licences d'équipe.

Créer un nouveau projet dans Visual Studio

Avant de plonger dans les exemples de code, mettons en place un environnement de développement approprié. Ouvrez Visual Studio et créez un nouveau projet :

  1. Accédez à Fichier > Nouveau > Projet
  2. Sélectionnez "Application console" (.NET Core ou .NET Framework)
  3. Choisissez votre framework cible (.NET 6.0 ou supérieur recommandé)
  4. Nommez votre projet (par exemple, "PdfLibraryComparison")
  5. Cliquez sur Créer

Créer un nouveau projet dans Visual Studio La boîte de dialogue de création de projet de Visual Studio pour la mise en place d'une nouvelle application .NET

Installation de la bibliothèque IronPDF C

Méthodes d'installation

IronPDF propose plusieurs approches d'installation pour s'adapter aux différents flux de travail de développement :

Méthode 1 : Utilisation du gestionnaire de paquets NuGet (Recommandé)

L'approche la plus simple consiste à utiliser le gestionnaire de paquets NuGet intégré à Visual Studio :

  1. Cliquez avec le bouton droit de la souris sur votre projet dans l'explorateur de solutions
  2. Sélectionnez "Manage NuGet Packages" (Gérer les paquets NuGet)
  3. Cliquez sur "Parcourir" et recherchez "IronPDF"
  4. Cliquez sur Installer sur le package officiel d'IronPDF

NuGet Package Manager montrant l'installation d'IronPDF Installation d'IronPDF via l'interface NuGet Package Manager de Visual Studio

Méthode 2 : Console du gestionnaire de paquets

Pour les développeurs qui préfèrent les outils en ligne de commande :

Install-Package IronPdf

Console de gestion des paquets installant IronPDF Utilisation de la console du gestionnaire de paquets pour installer IronPDF avec une seule commande

Méthode 3 : Téléchargement direct

Pour les environnements où l'accès à l'internet est restreint :

  1. Télécharger à partir de NuGet.org
  2. Ajouter le fichier .nupkg à un flux NuGet local
  3. Installer à partir de votre flux local

Méthode 4 : .NET CLI

Pour les projets .NET Core/5+ :

dotnet add package IronPdf

Installation d'ABCpdf

Méthodes d'installation

ABCpdf offre des options d'installation similaires avec quelques considérations supplémentaires :

Méthode 1 : Installation de NuGet

Install-Package ABCpdf -Version 13.0.0.0

Notez qu'ABCpdf a des paquets distincts pour les différentes éditions :

  • ABCpdf - Édition standard (32 bits uniquement)
  • ABCpdf.ABCChrome64 - Nécessaire pour le rendu de Chrome sur 64 bits
  • ABCpdf.ABCGecko - Pour le moteur de rendu Gecko

Méthode 2 : Installation manuelle

  1. Télécharger à partir de site web deWebSupergoo
  2. Extraire le fichier ZIP
  3. Ajouter des références aux DLL appropriées
  4. Copiez les dépendances natives dans votre répertoire de sortie

Considérations spécifiques à la plate-forme

ABCpdf nécessite une configuration supplémentaire pour les plates-formes non Windows :

<!-- For Linux deployment -->
<PackageReference Include="ABCpdf.Linux" Version="13.0.0.0" />
<!-- For Linux deployment -->
<PackageReference Include="ABCpdf.Linux" Version="13.0.0.0" />
XML

Comment ces bibliothèques gèrent-elles la conversion de HTML en PDF?

Comprendre les différences fondamentales dans la façon dont chaque bibliothèque aborde la conversion HTML vers PDF permet d'expliquer leurs différentes capacités et caractéristiques de performance.

L'approche d'IronPDF : Architecture Chrome-First

IronPDF utilise un moteur de navigateur Chrome complet, ce qui présente plusieurs avantages :

using IronPdf;

// IronPDF's approach - Chrome rendering with full browser capabilities
var renderer = new ChromePdfRenderer();

// Configure rendering to match Chrome's print preview exactly
renderer.RenderingOptions = ChromePdfRenderOptions.DefaultChrome;

// Or customize for specific needs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Wait for JS execution

// Convert complex HTML with modern CSS and JavaScript
string complexHtml = @"
<!DOCTYPE html>
<html>
<head>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;700&display=swap');

        .container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            font-family: 'Roboto', sans-serif;
        }

        .card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 10px;
            padding: 20px;
            color: white;
            box-shadow: 0 10px 20px rgba(0,0,0,0.19);
            transform: translateY(0);
            transition: transform 0.3s;
        }

        @media print {
            .card { break-inside: avoid; }
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='card'>
            <h2>Modern CSS Support</h2>
            <p>Grid, Flexbox, Gradients, Shadows - all rendered perfectly</p>
        </div>
        <div class='card'>
            <h2>Web Fonts</h2>
            <p>Google Fonts and custom fonts work seamlessly</p>
        </div>
    </div>
    <script>
        // Dynamic content generation
        document.addEventListener('DOMContentLoaded', function() {
            const container = document.querySelector('.container');
            const dynamicCard = document.createElement('div');
            dynamicCard.className = 'card';
            dynamicCard.innerHTML = '<h2>JavaScript Generated</h2><p>This card was added by JavaScript</p>';
            container.appendChild(dynamicCard);
        });
    </script>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(complexHtml);
pdf.SaveAs("modern-web-features.pdf");
using IronPdf;

// IronPDF's approach - Chrome rendering with full browser capabilities
var renderer = new ChromePdfRenderer();

// Configure rendering to match Chrome's print preview exactly
renderer.RenderingOptions = ChromePdfRenderOptions.DefaultChrome;

// Or customize for specific needs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Wait for JS execution

// Convert complex HTML with modern CSS and JavaScript
string complexHtml = @"
<!DOCTYPE html>
<html>
<head>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;700&display=swap');

        .container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            font-family: 'Roboto', sans-serif;
        }

        .card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 10px;
            padding: 20px;
            color: white;
            box-shadow: 0 10px 20px rgba(0,0,0,0.19);
            transform: translateY(0);
            transition: transform 0.3s;
        }

        @media print {
            .card { break-inside: avoid; }
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='card'>
            <h2>Modern CSS Support</h2>
            <p>Grid, Flexbox, Gradients, Shadows - all rendered perfectly</p>
        </div>
        <div class='card'>
            <h2>Web Fonts</h2>
            <p>Google Fonts and custom fonts work seamlessly</p>
        </div>
    </div>
    <script>
        // Dynamic content generation
        document.addEventListener('DOMContentLoaded', function() {
            const container = document.querySelector('.container');
            const dynamicCard = document.createElement('div');
            dynamicCard.className = 'card';
            dynamicCard.innerHTML = '<h2>JavaScript Generated</h2><p>This card was added by JavaScript</p>';
            container.appendChild(dynamicCard);
        });
    </script>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(complexHtml);
pdf.SaveAs("modern-web-features.pdf");
Imports IronPdf

' IronPDF's approach - Chrome rendering with full browser capabilities
Private renderer = New ChromePdfRenderer()

' Configure rendering to match Chrome's print preview exactly
renderer.RenderingOptions = ChromePdfRenderOptions.DefaultChrome

' Or customize for specific needs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' Wait for JS execution

' Convert complex HTML with modern CSS and JavaScript
Dim complexHtml As String = "
<!DOCTYPE html>
<html>
<head>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;700&display=swap');

        .container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            font-family: 'Roboto', sans-serif;
        }

        .card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 10px;
            padding: 20px;
            color: white;
            box-shadow: 0 10px 20px rgba(0,0,0,0.19);
            transform: translateY(0);
            transition: transform 0.3s;
        }

        @media print {
            .card { break-inside: avoid; }
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='card'>
            <h2>Modern CSS Support</h2>
            <p>Grid, Flexbox, Gradients, Shadows - all rendered perfectly</p>
        </div>
        <div class='card'>
            <h2>Web Fonts</h2>
            <p>Google Fonts and custom fonts work seamlessly</p>
        </div>
    </div>
    <script>
        // Dynamic content generation
        document.addEventListener('DOMContentLoaded', function() {
            const container = document.querySelector('.container');
            const dynamicCard = document.createElement('div');
            dynamicCard.className = 'card';
            dynamicCard.innerHTML = '<h2>JavaScript Generated</h2><p>This card was added by JavaScript</p>';
            container.appendChild(dynamicCard);
        });
    </script>
</body>
</html>"

Dim pdf = renderer.RenderHtmlAsPdf(complexHtml)
pdf.SaveAs("modern-web-features.pdf")
$vbLabelText   $csharpLabel

Ce code démontre plusieurs avantages clés de l'approche d'IronPDF basée sur Chrome :

  1. Support CSS moderne : Les mises en page en grille, flexbox, les dégradés et les transformations fonctionnent exactement comme dans Chrome
  2. Intégration des polices Web : Les polices Google se chargent automatiquement sans configuration supplémentaire
  3. Exécution JavaScript : La génération de contenu dynamique a lieu avant le rendu du PDF
  4. Questions multimédias : Les styles spécifiques à l'impression sont correctement appliqués

L'approche d'ABCpdf : Flexibilité multi-moteurs

ABCpdf propose plusieurs moteurs de rendu, chacun avec des capacités différentes :

using WebSupergoo.ABCpdf13;

// Méthode de travail1: Using ABCChrome engine (most modern)
Doc chromeDoc = new Doc();
chromeDoc.HtmlOptions.Engine = EngineType.Chrome;
chromeDoc.HtmlOptions.Chrome.SetUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

// Chrome engine supports modern web standards
int chromeId = chromeDoc.AddImageUrl("https://example.com");

// Chain pages if content overflows
while (chromeDoc.Chainable(chromeId))
{
    chromeDoc.Page = chromeDoc.AddPage();
    chromeId = chromeDoc.AddImageToChain(chromeId);
}

chromeDoc.Save("chrome-engine-output.pdf");

// Méthode de travail2: Using Gecko engine (Firefox-based)
Doc geckoDoc = new Doc();
geckoDoc.HtmlOptions.Engine = EngineType.Gecko;
geckoDoc.HtmlOptions.UseScript = true; // Enable JavaScript

// Gecko provides good standards support with lower resource usage
string html = "<html><body><h1>Gecko Rendered Content</h1></body></html>";
geckoDoc.AddImageHtml(html);
geckoDoc.Save("gecko-engine-output.pdf");

// Méthode de travail3: Using MSHTML engine (IE-based, legacy support)
Doc ieDoc = new Doc();
ieDoc.HtmlOptions.Engine = EngineType.MSHtml;

// MSHTML is faster but with limited modern CSS support
ieDoc.AddImageUrl("https://legacy-app.example.com");
ieDoc.Save("ie-engine-output.pdf");
using WebSupergoo.ABCpdf13;

// Méthode de travail1: Using ABCChrome engine (most modern)
Doc chromeDoc = new Doc();
chromeDoc.HtmlOptions.Engine = EngineType.Chrome;
chromeDoc.HtmlOptions.Chrome.SetUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

// Chrome engine supports modern web standards
int chromeId = chromeDoc.AddImageUrl("https://example.com");

// Chain pages if content overflows
while (chromeDoc.Chainable(chromeId))
{
    chromeDoc.Page = chromeDoc.AddPage();
    chromeId = chromeDoc.AddImageToChain(chromeId);
}

chromeDoc.Save("chrome-engine-output.pdf");

// Méthode de travail2: Using Gecko engine (Firefox-based)
Doc geckoDoc = new Doc();
geckoDoc.HtmlOptions.Engine = EngineType.Gecko;
geckoDoc.HtmlOptions.UseScript = true; // Enable JavaScript

// Gecko provides good standards support with lower resource usage
string html = "<html><body><h1>Gecko Rendered Content</h1></body></html>";
geckoDoc.AddImageHtml(html);
geckoDoc.Save("gecko-engine-output.pdf");

// Méthode de travail3: Using MSHTML engine (IE-based, legacy support)
Doc ieDoc = new Doc();
ieDoc.HtmlOptions.Engine = EngineType.MSHtml;

// MSHTML is faster but with limited modern CSS support
ieDoc.AddImageUrl("https://legacy-app.example.com");
ieDoc.Save("ie-engine-output.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

L'approche multi-moteurs offre une certaine flexibilité mais nécessite une réflexion approfondie :

  1. Sélection du moteur : Les développeurs doivent choisir le moteur approprié pour leur contenu
  2. Parité des fonctionnalités : Différents moteurs prennent en charge différentes fonctionnalités HTML/CSS
  3. Complexité du déploiement : Chaque moteur peut avoir des exigences différentes en matière d'exécution
  4. Frais généraux de test : Les résultats peuvent varier d'un moteur à l'autre, ce qui nécessite davantage de tests

Créer des documents PDF à partir d'URL

L'un des cas d'utilisation les plus courants des bibliothèques PDF est la conversion de pages web en direct en documents PDF. Voyons comment chaque bibliothèque s'acquitte de cette tâche.

Utilisation d'IronPDF

La conversion d'URL en PDF d'IronPDF tire parti de l'intégralité du moteur du navigateur Chrome :

using IronPdf;
using System;
using System.Threading.Tasks;

public class UrlToPdfConverter
{
    public static async Task ConvertUrlToPdfAsync()
    {
        var renderer = new ChromePdfRenderer();

        // Configure for optimal web page capture
        renderer.RenderingOptions = new ChromePdfRenderOptions
        {
            // Viewport and scaling
            ViewPortWidth = 1920,
            ViewPortHeight = 1080,
            ZoomLevel = 100,

            // Paper and margins
            PaperSize = PdfPaperSize.A4,
            MarginTop = 10,
            MarginBottom = 10,
            MarginLeft = 10,
            MarginRight = 10,

            // Rendering behavior
            CssMediaType = PdfCssMediaType.Screen,
            PrintHtmlBackgrounds = true,
            CreatePdfFormsFromHtml = true,

            // JavaScript and timing
            EnableJavaScript = true,
            WaitFor = new WaitFor
            {
                // Wait strategies for dynamic content
                RenderDelay = 500, // milliseconds
                JavaScriptFinishDelay = 100,
                AllowedExecutionTime = 30000 // 30 seconds max
            }
        };

        // Handle authentication if needed
        renderer.RenderingOptions.HttpOptions.HttpHeaders.Add("Authorization", "Bearer your-token");

        // Convert with error handling
        try
        {
            // Async conversion for better performance
            var pdf = await renderer.RenderUrlAsPdfAsync("https://github.com/trending");

            // Add metadata
            pdf.MetaData.Author = "IronPDF Example";
            pdf.MetaData.Title = "GitHub Trending Projects";
            pdf.MetaData.CreationDate = DateTime.Now;

            // Add watermark
            pdf.ApplyWatermark("<h2 style='color:red;opacity:0.5'>CONFIDENTIAL</h2>", 
                30, VerticalAlignment.Middle, HorizontalAlignment.Center);

            pdf.SaveAs("github-trending.pdf");
            Console.WriteLine("PDF created successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error creating PDF: {ex.Message}");
        }
    }
}
using IronPdf;
using System;
using System.Threading.Tasks;

public class UrlToPdfConverter
{
    public static async Task ConvertUrlToPdfAsync()
    {
        var renderer = new ChromePdfRenderer();

        // Configure for optimal web page capture
        renderer.RenderingOptions = new ChromePdfRenderOptions
        {
            // Viewport and scaling
            ViewPortWidth = 1920,
            ViewPortHeight = 1080,
            ZoomLevel = 100,

            // Paper and margins
            PaperSize = PdfPaperSize.A4,
            MarginTop = 10,
            MarginBottom = 10,
            MarginLeft = 10,
            MarginRight = 10,

            // Rendering behavior
            CssMediaType = PdfCssMediaType.Screen,
            PrintHtmlBackgrounds = true,
            CreatePdfFormsFromHtml = true,

            // JavaScript and timing
            EnableJavaScript = true,
            WaitFor = new WaitFor
            {
                // Wait strategies for dynamic content
                RenderDelay = 500, // milliseconds
                JavaScriptFinishDelay = 100,
                AllowedExecutionTime = 30000 // 30 seconds max
            }
        };

        // Handle authentication if needed
        renderer.RenderingOptions.HttpOptions.HttpHeaders.Add("Authorization", "Bearer your-token");

        // Convert with error handling
        try
        {
            // Async conversion for better performance
            var pdf = await renderer.RenderUrlAsPdfAsync("https://github.com/trending");

            // Add metadata
            pdf.MetaData.Author = "IronPDF Example";
            pdf.MetaData.Title = "GitHub Trending Projects";
            pdf.MetaData.CreationDate = DateTime.Now;

            // Add watermark
            pdf.ApplyWatermark("<h2 style='color:red;opacity:0.5'>CONFIDENTIAL</h2>", 
                30, VerticalAlignment.Middle, HorizontalAlignment.Center);

            pdf.SaveAs("github-trending.pdf");
            Console.WriteLine("PDF created successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error creating PDF: {ex.Message}");
        }
    }
}
Imports IronPdf
Imports System
Imports System.Threading.Tasks

Public Class UrlToPdfConverter
	Public Shared Async Function ConvertUrlToPdfAsync() As Task
		Dim renderer = New ChromePdfRenderer()

		' Configure for optimal web page capture
		renderer.RenderingOptions = New ChromePdfRenderOptions With {
			.ViewPortWidth = 1920,
			.ViewPortHeight = 1080,
			.ZoomLevel = 100,
			.PaperSize = PdfPaperSize.A4,
			.MarginTop = 10,
			.MarginBottom = 10,
			.MarginLeft = 10,
			.MarginRight = 10,
			.CssMediaType = PdfCssMediaType.Screen,
			.PrintHtmlBackgrounds = True,
			.CreatePdfFormsFromHtml = True,
			.EnableJavaScript = True,
			.WaitFor = New WaitFor With {
				.RenderDelay = 500,
				.JavaScriptFinishDelay = 100,
				.AllowedExecutionTime = 30000
			}
		}

		' Handle authentication if needed
		renderer.RenderingOptions.HttpOptions.HttpHeaders.Add("Authorization", "Bearer your-token")

		' Convert with error handling
		Try
			' Async conversion for better performance
			Dim pdf = Await renderer.RenderUrlAsPdfAsync("https://github.com/trending")

			' Add metadata
			pdf.MetaData.Author = "IronPDF Example"
			pdf.MetaData.Title = "GitHub Trending Projects"
			pdf.MetaData.CreationDate = DateTime.Now

			' Add watermark
			pdf.ApplyWatermark("<h2 style='color:red;opacity:0.5'>CONFIDENTIAL</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)

			pdf.SaveAs("github-trending.pdf")
			Console.WriteLine("PDF created successfully!")
		Catch ex As Exception
			Console.WriteLine($"Error creating PDF: {ex.Message}")
		End Try
	End Function
End Class
$vbLabelText   $csharpLabel

Les principales caractéristiques ont été démontrées :

  • Viewport Control : simuler différentes tailles d'écran pour des tests réactifs
  • <Prise en charge de l'authentification : Ajout d'en-têtes pour les ressources protégées
  • Gestion dynamique du contenu : Stratégies d'attente pour les pages à forte composante JavaScript
  • Post-Traitement : Ajout de métadonnées et de filigranes après la conversion

Utiliser ABCpdf

Conversion d'URL d'ABCpdf avec chaînage de pages :

using WebSupergoo.ABCpdf13;
using System;

public class ABCpdfUrlConverter
{
    public static void ConvertUrlWithABCpdf()
    {
        using (Doc theDoc = new Doc())
        {
            // Configure the HTML engine
            theDoc.HtmlOptions.Engine = EngineType.Chrome;
            theDoc.HtmlOptions.Chrome.LoadDelay = 1000; // Wait 1 second

            // Set viewport size
            theDoc.HtmlOptions.BrowserWidth = 1200;

            // Authentication
            theDoc.HtmlOptions.HttpAdditionalHeaders = "Authorization: Bearer your-token";

            // Page setup
            theDoc.Rect.Inset(20, 20);
            theDoc.Page = theDoc.AddPage();

            // Add the URL
            int theID = theDoc.AddImageUrl("https://github.com/trending");

            // Chain pages for overflow content
            while (true)
            {
                if (!theDoc.Chainable(theID))
                    break;
                theDoc.Page = theDoc.AddPage();
                theID = theDoc.AddImageToChain(theID);
            }

            // Reduce file size
            for (int i = 1; i <= theDoc.PageCount; i++)
            {
                theDoc.PageNumber = i;
                theDoc.Flatten();
            }

            // Save
            theDoc.Save("abcpdf-github.pdf");
        }
    }
}
using WebSupergoo.ABCpdf13;
using System;

public class ABCpdfUrlConverter
{
    public static void ConvertUrlWithABCpdf()
    {
        using (Doc theDoc = new Doc())
        {
            // Configure the HTML engine
            theDoc.HtmlOptions.Engine = EngineType.Chrome;
            theDoc.HtmlOptions.Chrome.LoadDelay = 1000; // Wait 1 second

            // Set viewport size
            theDoc.HtmlOptions.BrowserWidth = 1200;

            // Authentication
            theDoc.HtmlOptions.HttpAdditionalHeaders = "Authorization: Bearer your-token";

            // Page setup
            theDoc.Rect.Inset(20, 20);
            theDoc.Page = theDoc.AddPage();

            // Add the URL
            int theID = theDoc.AddImageUrl("https://github.com/trending");

            // Chain pages for overflow content
            while (true)
            {
                if (!theDoc.Chainable(theID))
                    break;
                theDoc.Page = theDoc.AddPage();
                theID = theDoc.AddImageToChain(theID);
            }

            // Reduce file size
            for (int i = 1; i <= theDoc.PageCount; i++)
            {
                theDoc.PageNumber = i;
                theDoc.Flatten();
            }

            // Save
            theDoc.Save("abcpdf-github.pdf");
        }
    }
}
Imports WebSupergoo.ABCpdf13
Imports System

Public Class ABCpdfUrlConverter
	Public Shared Sub ConvertUrlWithABCpdf()
		Using theDoc As New Doc()
			' Configure the HTML engine
			theDoc.HtmlOptions.Engine = EngineType.Chrome
			theDoc.HtmlOptions.Chrome.LoadDelay = 1000 ' Wait 1 second

			' Set viewport size
			theDoc.HtmlOptions.BrowserWidth = 1200

			' Authentication
			theDoc.HtmlOptions.HttpAdditionalHeaders = "Authorization: Bearer your-token"

			' Page setup
			theDoc.Rect.Inset(20, 20)
			theDoc.Page = theDoc.AddPage()

			' Add the URL
			Dim theID As Integer = theDoc.AddImageUrl("https://github.com/trending")

			' Chain pages for overflow content
			Do
				If Not theDoc.Chainable(theID) Then
					Exit Do
				End If
				theDoc.Page = theDoc.AddPage()
				theID = theDoc.AddImageToChain(theID)
			Loop

			' Reduce file size
			For i As Integer = 1 To theDoc.PageCount
				theDoc.PageNumber = i
				theDoc.Flatten()
			Next i

			' Save
			theDoc.Save("abcpdf-github.pdf")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Différences notables :

  • Chaînage de pages : Traitement manuel du contenu de plusieurs pages
  • Configuration du moteur : Doit choisir explicitement le moteur de rendu
  • Gestion des ressources : Nécessite une élimination appropriée avec la mention utiliser

Créer des PDF à partir de chaînes HTML

Les deux bibliothèques excellent dans la conversion de chaînes HTML en PDF, mais leurs approches diffèrent considérablement.

Utilisation d'IronPDF

La conversion de chaînes HTML d'IronPDF avec des fonctionnalités avancées :

using IronPdf;
using System.IO;

public class HtmlStringToPdf
{
    public static void GenerateInvoicePdf()
    {
        var renderer = new ChromePdfRenderer();

        // Configure for print-quality output
        renderer.RenderingOptions = new ChromePdfRenderOptions
        {
            PaperSize = PdfPaperSize.A4,
            DPI = 300, // High quality print
            CssMediaType = PdfCssMediaType.Print,
            PaperFit = new PaperFit
            {
                UseFitToPageRendering = true,
                RenderScale = 100
            }
        };

        // Professional invoice HTML
        string invoiceHtml = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        @page {
            size: A4;
            margin: 0;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            margin: 0;
            padding: 20mm;
            color: #333;
        }

        .invoice-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 30px;
            border-bottom: 2px solid #0066cc;
            padding-bottom: 20px;
        }

        .company-info h1 {
            color: #0066cc;
            margin: 0;
            font-size: 28px;
        }

        .invoice-details {
            text-align: right;
        }

        .invoice-details h2 {
            color: #666;
            margin: 0 0 10px 0;
            font-size: 24px;
        }

        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 30px;
        }

        .invoice-table th {
            background-color: #0066cc;
            color: white;
            padding: 12px;
            text-align: left;
        }

        .invoice-table td {
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }

        .invoice-table tr:hover {
            background-color: #f5f5f5;
        }

        .total-section {
            margin-top: 30px;
            text-align: right;
        }

        .total-section .total-row {
            display: flex;
            justify-content: flex-end;
            margin: 5px 0;
        }

        .total-section .label {
            font-weight: bold;
            margin-right: 20px;
            min-width: 100px;
        }

        .total-section .grand-total {
            font-size: 20px;
            color: #0066cc;
            border-top: 2px solid #0066cc;
            padding-top: 10px;
            margin-top: 10px;
        }

        @media print {
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class='invoice-header'>
        <div class='company-info'>
            <h1>ACME Corporation</h1>
            <p>123 Business Street<br>
            New York, NY 10001<br>
            Phone: (555) 123-4567<br>
            Email: billing@acme.com</p>
        </div>
        <div class='invoice-details'>
            <h2>INVOICE</h2>
            <p><strong>Invoice #:</strong> INV-2025-001<br>
            <strong>Date:</strong> " + DateTime.Now.ToString("MMMM dd, yyyy") + @"<br>
            <strong>Due Date:</strong> " + DateTime.Now.AddDays(30).ToString("MMMM dd, yyyy") + @"</p>
        </div>
    </div>

    <div class='billing-info'>
        <h3>Bill To:</h3>
        <p>John Doe<br>
        456 Client Avenue<br>
        Los Angeles, CA 90001</p>
    </div>

    <table class='invoice-table'>
        <thead>
            <tr>
                <th>Description</th>
                <th>Quantity</th>
                <th>Unit Price</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Professional Services - Web Development</td>
                <td>40 hours</td>
                <td>$150.00</td>
                <td>$6,000.00</td>
            </tr>
            <tr>
                <td>Hosting Services (Annual)</td>
                <td>1</td>
                <td>$1,200.00</td>
                <td>$1,200.00</td>
            </tr>
            <tr>
                <td>Domain Registration</td>
                <td>2</td>
                <td>$15.00</td>
                <td>$30.00</td>
            </tr>
        </tbody>
    </table>

    <div class='total-section'>
        <div class='total-row'>
            <span class='label'>Subtotal:</span>
            <span>$7,230.00</span>
        </div>
        <div class='total-row'>
            <span class='label'>Tax (8%):</span>
            <span>$578.40</span>
        </div>
        <div class='total-row grand-total'>
            <span class='label'>Total Due:</span>
            <span>$7,808.40</span>
        </div>
    </div>

    <div class='footer' style='margin-top: 50px; padding-top: 20px; border-top: 1px solid #ddd; text-align: center; color: #666;'>
        <p>Thank you for your business!<br>
        Payment is due within 30 days. Please include invoice number with payment.</p>
    </div>
</body>
</html>";

        // Generate PDF with base path for local assets
        var pdf = renderer.RenderHtmlAsPdf(invoiceHtml, @"C:\Assets\");

        // Add security
        pdf.SecuritySettings.AllowUserEditing = false;
        pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
        pdf.SecuritySettings.OwnerPassword = "admin123";

        // Save with optimization
        pdf.CompressImages(60); // 60% quality for smaller file size
        pdf.SaveAs("professional-invoice.pdf");
    }
}
using IronPdf;
using System.IO;

public class HtmlStringToPdf
{
    public static void GenerateInvoicePdf()
    {
        var renderer = new ChromePdfRenderer();

        // Configure for print-quality output
        renderer.RenderingOptions = new ChromePdfRenderOptions
        {
            PaperSize = PdfPaperSize.A4,
            DPI = 300, // High quality print
            CssMediaType = PdfCssMediaType.Print,
            PaperFit = new PaperFit
            {
                UseFitToPageRendering = true,
                RenderScale = 100
            }
        };

        // Professional invoice HTML
        string invoiceHtml = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        @page {
            size: A4;
            margin: 0;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            margin: 0;
            padding: 20mm;
            color: #333;
        }

        .invoice-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 30px;
            border-bottom: 2px solid #0066cc;
            padding-bottom: 20px;
        }

        .company-info h1 {
            color: #0066cc;
            margin: 0;
            font-size: 28px;
        }

        .invoice-details {
            text-align: right;
        }

        .invoice-details h2 {
            color: #666;
            margin: 0 0 10px 0;
            font-size: 24px;
        }

        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 30px;
        }

        .invoice-table th {
            background-color: #0066cc;
            color: white;
            padding: 12px;
            text-align: left;
        }

        .invoice-table td {
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }

        .invoice-table tr:hover {
            background-color: #f5f5f5;
        }

        .total-section {
            margin-top: 30px;
            text-align: right;
        }

        .total-section .total-row {
            display: flex;
            justify-content: flex-end;
            margin: 5px 0;
        }

        .total-section .label {
            font-weight: bold;
            margin-right: 20px;
            min-width: 100px;
        }

        .total-section .grand-total {
            font-size: 20px;
            color: #0066cc;
            border-top: 2px solid #0066cc;
            padding-top: 10px;
            margin-top: 10px;
        }

        @media print {
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class='invoice-header'>
        <div class='company-info'>
            <h1>ACME Corporation</h1>
            <p>123 Business Street<br>
            New York, NY 10001<br>
            Phone: (555) 123-4567<br>
            Email: billing@acme.com</p>
        </div>
        <div class='invoice-details'>
            <h2>INVOICE</h2>
            <p><strong>Invoice #:</strong> INV-2025-001<br>
            <strong>Date:</strong> " + DateTime.Now.ToString("MMMM dd, yyyy") + @"<br>
            <strong>Due Date:</strong> " + DateTime.Now.AddDays(30).ToString("MMMM dd, yyyy") + @"</p>
        </div>
    </div>

    <div class='billing-info'>
        <h3>Bill To:</h3>
        <p>John Doe<br>
        456 Client Avenue<br>
        Los Angeles, CA 90001</p>
    </div>

    <table class='invoice-table'>
        <thead>
            <tr>
                <th>Description</th>
                <th>Quantity</th>
                <th>Unit Price</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Professional Services - Web Development</td>
                <td>40 hours</td>
                <td>$150.00</td>
                <td>$6,000.00</td>
            </tr>
            <tr>
                <td>Hosting Services (Annual)</td>
                <td>1</td>
                <td>$1,200.00</td>
                <td>$1,200.00</td>
            </tr>
            <tr>
                <td>Domain Registration</td>
                <td>2</td>
                <td>$15.00</td>
                <td>$30.00</td>
            </tr>
        </tbody>
    </table>

    <div class='total-section'>
        <div class='total-row'>
            <span class='label'>Subtotal:</span>
            <span>$7,230.00</span>
        </div>
        <div class='total-row'>
            <span class='label'>Tax (8%):</span>
            <span>$578.40</span>
        </div>
        <div class='total-row grand-total'>
            <span class='label'>Total Due:</span>
            <span>$7,808.40</span>
        </div>
    </div>

    <div class='footer' style='margin-top: 50px; padding-top: 20px; border-top: 1px solid #ddd; text-align: center; color: #666;'>
        <p>Thank you for your business!<br>
        Payment is due within 30 days. Please include invoice number with payment.</p>
    </div>
</body>
</html>";

        // Generate PDF with base path for local assets
        var pdf = renderer.RenderHtmlAsPdf(invoiceHtml, @"C:\Assets\");

        // Add security
        pdf.SecuritySettings.AllowUserEditing = false;
        pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
        pdf.SecuritySettings.OwnerPassword = "admin123";

        // Save with optimization
        pdf.CompressImages(60); // 60% quality for smaller file size
        pdf.SaveAs("professional-invoice.pdf");
    }
}
Imports IronPdf
Imports System.IO

Public Class HtmlStringToPdf
	Public Shared Sub GenerateInvoicePdf()
		Dim renderer = New ChromePdfRenderer()

		' Configure for print-quality output
		renderer.RenderingOptions = New ChromePdfRenderOptions With {
			.PaperSize = PdfPaperSize.A4,
			.DPI = 300,
			.CssMediaType = PdfCssMediaType.Print,
			.PaperFit = New PaperFit With {
				.UseFitToPageRendering = True,
				.RenderScale = 100
			}
		}

		' Professional invoice HTML
		Dim invoiceHtml As String = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        @page {
            size: A4;
            margin: 0;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            margin: 0;
            padding: 20mm;
            color: #333;
        }

        .invoice-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 30px;
            border-bottom: 2px solid #0066cc;
            padding-bottom: 20px;
        }

        .company-info h1 {
            color: #0066cc;
            margin: 0;
            font-size: 28px;
        }

        .invoice-details {
            text-align: right;
        }

        .invoice-details h2 {
            color: #666;
            margin: 0 0 10px 0;
            font-size: 24px;
        }

        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 30px;
        }

        .invoice-table th {
            background-color: #0066cc;
            color: white;
            padding: 12px;
            text-align: left;
        }

        .invoice-table td {
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }

        .invoice-table tr:hover {
            background-color: #f5f5f5;
        }

        .total-section {
            margin-top: 30px;
            text-align: right;
        }

        .total-section .total-row {
            display: flex;
            justify-content: flex-end;
            margin: 5px 0;
        }

        .total-section .label {
            font-weight: bold;
            margin-right: 20px;
            min-width: 100px;
        }

        .total-section .grand-total {
            font-size: 20px;
            color: #0066cc;
            border-top: 2px solid #0066cc;
            padding-top: 10px;
            margin-top: 10px;
        }

        @media print {
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class='invoice-header'>
        <div class='company-info'>
            <h1>ACME Corporation</h1>
            <p>123 Business Street<br>
            New York, NY 10001<br>
            Phone: (555) 123-4567<br>
            Email: billing@acme.com</p>
        </div>
        <div class='invoice-details'>
            <h2>INVOICE</h2>
            <p><strong>Invoice #:</strong> INV-2025-001<br>
            <strong>Date:</strong> " & DateTime.Now.ToString("MMMM dd, yyyy") & "<br>
            <strong>Due Date:</strong> " & DateTime.Now.AddDays(30).ToString("MMMM dd, yyyy") & "</p>
        </div>
    </div>

    <div class='billing-info'>
        <h3>Bill To:</h3>
        <p>John Doe<br>
        456 Client Avenue<br>
        Los Angeles, CA 90001</p>
    </div>

    <table class='invoice-table'>
        <thead>
            <tr>
                <th>Description</th>
                <th>Quantity</th>
                <th>Unit Price</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Professional Services - Web Development</td>
                <td>40 hours</td>
                <td>$150.00</td>
                <td>$6,000.00</td>
            </tr>
            <tr>
                <td>Hosting Services (Annual)</td>
                <td>1</td>
                <td>$1,200.00</td>
                <td>$1,200.00</td>
            </tr>
            <tr>
                <td>Domain Registration</td>
                <td>2</td>
                <td>$15.00</td>
                <td>$30.00</td>
            </tr>
        </tbody>
    </table>

    <div class='total-section'>
        <div class='total-row'>
            <span class='label'>Subtotal:</span>
            <span>$7,230.00</span>
        </div>
        <div class='total-row'>
            <span class='label'>Tax (8%):</span>
            <span>$578.40</span>
        </div>
        <div class='total-row grand-total'>
            <span class='label'>Total Due:</span>
            <span>$7,808.40</span>
        </div>
    </div>

    <div class='footer' style='margin-top: 50px; padding-top: 20px; border-top: 1px solid #ddd; text-align: center; color: #666;'>
        <p>Thank you for your business!<br>
        Payment is due within 30 days. Please include invoice number with payment.</p>
    </div>
</body>
</html>"

		' Generate PDF with base path for local assets
		Dim pdf = renderer.RenderHtmlAsPdf(invoiceHtml, "C:\Assets\")

		' Add security
		pdf.SecuritySettings.AllowUserEditing = False
		pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
		pdf.SecuritySettings.OwnerPassword = "admin123"

		' Save with optimization
		pdf.CompressImages(60) ' 60% quality for smaller file size
		pdf.SaveAs("professional-invoice.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Cet exemple illustre :

  • Mise en page professionnelle : CSS complexes avec flexbox et grid
  • Contenu dynamique : Calculs et formatage des dates
  • Optimisation de l'impression : Requêtes de médias pour un style spécifique à l'impression
  • Fonctionnalités de sécurité : Protection par mot de passe et paramètres d'autorisation
  • Optimisation des fichiers : compression d'images pour réduire la taille des fichiers

Utiliser ABCpdf

Gestion des chaînes HTML d'ABCpdf avec texte stylisé :

using WebSupergoo.ABCpdf13;

public class ABCpdfHtmlString
{
    public static void CreateStyledDocument()
    {
        using (Doc theDoc = new Doc())
        {
            // Set up the document
            theDoc.Rect.Inset(40, 40);
            theDoc.Color.String = "0 0 0"; // Black text

            // Add styled HTML content
            theDoc.FontSize = 48;
            string styledHtml = @"
                <h1 style='color: #0066cc'>ABCpdf Document</h1>
                <p style='font-size: 14pt; line-height: 1.5'>
                    This demonstrates <b>bold text</b>, <i>italic text</i>, 
                    and <span style='color: red'>colored text</span>.
                </p>
                <ul style='margin-left: 20px'>
                    <li>First item</li>
                    <li>Second item</li>
                    <li>Third item</li>
                </ul>";

            // Add HTML with automatic text flow
            int theID = theDoc.AddImageHtml(styledHtml);

            // Continue on new pages if needed
            while (true)
            {
                if (!theDoc.Chainable(theID))
                    break;
                theDoc.Page = theDoc.AddPage();
                theID = theDoc.AddImageToChain(theID);
            }

            // Apply compression
            theDoc.Encryption.Type = 2; // 128-bit encryption
            theDoc.Encryption.CanPrint = true;
            theDoc.Encryption.CanModify = false;

            theDoc.Save("styled-abcpdf.pdf");
        }
    }
}
using WebSupergoo.ABCpdf13;

public class ABCpdfHtmlString
{
    public static void CreateStyledDocument()
    {
        using (Doc theDoc = new Doc())
        {
            // Set up the document
            theDoc.Rect.Inset(40, 40);
            theDoc.Color.String = "0 0 0"; // Black text

            // Add styled HTML content
            theDoc.FontSize = 48;
            string styledHtml = @"
                <h1 style='color: #0066cc'>ABCpdf Document</h1>
                <p style='font-size: 14pt; line-height: 1.5'>
                    This demonstrates <b>bold text</b>, <i>italic text</i>, 
                    and <span style='color: red'>colored text</span>.
                </p>
                <ul style='margin-left: 20px'>
                    <li>First item</li>
                    <li>Second item</li>
                    <li>Third item</li>
                </ul>";

            // Add HTML with automatic text flow
            int theID = theDoc.AddImageHtml(styledHtml);

            // Continue on new pages if needed
            while (true)
            {
                if (!theDoc.Chainable(theID))
                    break;
                theDoc.Page = theDoc.AddPage();
                theID = theDoc.AddImageToChain(theID);
            }

            // Apply compression
            theDoc.Encryption.Type = 2; // 128-bit encryption
            theDoc.Encryption.CanPrint = true;
            theDoc.Encryption.CanModify = false;

            theDoc.Save("styled-abcpdf.pdf");
        }
    }
}
Imports WebSupergoo.ABCpdf13

Public Class ABCpdfHtmlString
	Public Shared Sub CreateStyledDocument()
		Using theDoc As New Doc()
			' Set up the document
			theDoc.Rect.Inset(40, 40)
			theDoc.Color.String = "0 0 0" ' Black text

			' Add styled HTML content
			theDoc.FontSize = 48
			Dim styledHtml As String = "
                <h1 style='color: #0066cc'>ABCpdf Document</h1>
                <p style='font-size: 14pt; line-height: 1.5'>
                    This demonstrates <b>bold text</b>, <i>italic text</i>, 
                    and <span style='color: red'>colored text</span>.
                </p>
                <ul style='margin-left: 20px'>
                    <li>First item</li>
                    <li>Second item</li>
                    <li>Third item</li>
                </ul>"

			' Add HTML with automatic text flow
			Dim theID As Integer = theDoc.AddImageHtml(styledHtml)

			' Continue on new pages if needed
			Do
				If Not theDoc.Chainable(theID) Then
					Exit Do
				End If
				theDoc.Page = theDoc.AddPage()
				theID = theDoc.AddImageToChain(theID)
			Loop

			' Apply compression
			theDoc.Encryption.Type = 2 ' 128-bit encryption
			theDoc.Encryption.CanPrint = True
			theDoc.Encryption.CanModify = False

			theDoc.Save("styled-abcpdf.pdf")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Analyse comparative des performances

La compréhension des caractéristiques de performance permet de choisir la bibliothèque la mieux adaptée à votre cas d'utilisation spécifique.

Configuration du test de référence

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using IronPdf;
using WebSupergoo.ABCpdf13;

[MemoryDiagnoser]
[SimpleJob(warmupCount: 3, targetCount: 10)]
public class PdfGenerationBenchmark
{
    private string _simpleHtml;
    private string _complexHtml;
    private ChromePdfRenderer _ironPdfRenderer;
    private Doc _abcPdfDoc;

    [GlobalSetup]
    public void Setup()
    {
        _simpleHtml = "<h1>Simple Document</h1><p>Basic paragraph text.</p>";
        _complexHtml = File.ReadAllText("complex-page.html"); // 50KB HTML with CSS/JS

        _ironPdfRenderer = new ChromePdfRenderer();
        _abcPdfDoc = new Doc();
        _abcPdfDoc.HtmlOptions.Engine = EngineType.Chrome;
    }

    [Benchmark]
    public void IronPDF_SimpleHtml()
    {
        var pdf = _ironPdfRenderer.RenderHtmlAsPdf(_simpleHtml);
        pdf.SaveAs("temp_iron_simple.pdf");
    }

    [Benchmark]
    public void ABCpdf_SimpleHtml()
    {
        _abcPdfDoc.Clear();
        _abcPdfDoc.AddImageHtml(_simpleHtml);
        _abcPdfDoc.Save("temp_abc_simple.pdf");
    }

    [Benchmark]
    public void IronPDF_ComplexHtml()
    {
        var pdf = _ironPdfRenderer.RenderHtmlAsPdf(_complexHtml);
        pdf.SaveAs("temp_iron_complex.pdf");
    }

    [Benchmark]
    public void ABCpdf_ComplexHtml()
    {
        _abcPdfDoc.Clear();
        int id = _abcPdfDoc.AddImageHtml(_complexHtml);
        while (_abcPdfDoc.Chainable(id))
        {
            _abcPdfDoc.Page = _abcPdfDoc.AddPage();
            id = _abcPdfDoc.AddImageToChain(id);
        }
        _abcPdfDoc.Save("temp_abc_complex.pdf");
    }
}
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using IronPdf;
using WebSupergoo.ABCpdf13;

[MemoryDiagnoser]
[SimpleJob(warmupCount: 3, targetCount: 10)]
public class PdfGenerationBenchmark
{
    private string _simpleHtml;
    private string _complexHtml;
    private ChromePdfRenderer _ironPdfRenderer;
    private Doc _abcPdfDoc;

    [GlobalSetup]
    public void Setup()
    {
        _simpleHtml = "<h1>Simple Document</h1><p>Basic paragraph text.</p>";
        _complexHtml = File.ReadAllText("complex-page.html"); // 50KB HTML with CSS/JS

        _ironPdfRenderer = new ChromePdfRenderer();
        _abcPdfDoc = new Doc();
        _abcPdfDoc.HtmlOptions.Engine = EngineType.Chrome;
    }

    [Benchmark]
    public void IronPDF_SimpleHtml()
    {
        var pdf = _ironPdfRenderer.RenderHtmlAsPdf(_simpleHtml);
        pdf.SaveAs("temp_iron_simple.pdf");
    }

    [Benchmark]
    public void ABCpdf_SimpleHtml()
    {
        _abcPdfDoc.Clear();
        _abcPdfDoc.AddImageHtml(_simpleHtml);
        _abcPdfDoc.Save("temp_abc_simple.pdf");
    }

    [Benchmark]
    public void IronPDF_ComplexHtml()
    {
        var pdf = _ironPdfRenderer.RenderHtmlAsPdf(_complexHtml);
        pdf.SaveAs("temp_iron_complex.pdf");
    }

    [Benchmark]
    public void ABCpdf_ComplexHtml()
    {
        _abcPdfDoc.Clear();
        int id = _abcPdfDoc.AddImageHtml(_complexHtml);
        while (_abcPdfDoc.Chainable(id))
        {
            _abcPdfDoc.Page = _abcPdfDoc.AddPage();
            id = _abcPdfDoc.AddImageToChain(id);
        }
        _abcPdfDoc.Save("temp_abc_complex.pdf");
    }
}
Imports BenchmarkDotNet.Attributes
Imports BenchmarkDotNet.Running
Imports IronPdf
Imports WebSupergoo.ABCpdf13

<MemoryDiagnoser>
<SimpleJob(warmupCount:= 3, targetCount:= 10)>
Public Class PdfGenerationBenchmark
	Private _simpleHtml As String
	Private _complexHtml As String
	Private _ironPdfRenderer As ChromePdfRenderer
	Private _abcPdfDoc As Doc

	<GlobalSetup>
	Public Sub Setup()
		_simpleHtml = "<h1>Simple Document</h1><p>Basic paragraph text.</p>"
		_complexHtml = File.ReadAllText("complex-page.html") ' 50KB HTML with CSS/JS

		_ironPdfRenderer = New ChromePdfRenderer()
		_abcPdfDoc = New Doc()
		_abcPdfDoc.HtmlOptions.Engine = EngineType.Chrome
	End Sub

	<Benchmark>
	Public Sub IronPDF_SimpleHtml()
		Dim pdf = _ironPdfRenderer.RenderHtmlAsPdf(_simpleHtml)
		pdf.SaveAs("temp_iron_simple.pdf")
	End Sub

	<Benchmark>
	Public Sub ABCpdf_SimpleHtml()
		_abcPdfDoc.Clear()
		_abcPdfDoc.AddImageHtml(_simpleHtml)
		_abcPdfDoc.Save("temp_abc_simple.pdf")
	End Sub

	<Benchmark>
	Public Sub IronPDF_ComplexHtml()
		Dim pdf = _ironPdfRenderer.RenderHtmlAsPdf(_complexHtml)
		pdf.SaveAs("temp_iron_complex.pdf")
	End Sub

	<Benchmark>
	Public Sub ABCpdf_ComplexHtml()
		_abcPdfDoc.Clear()
		Dim id As Integer = _abcPdfDoc.AddImageHtml(_complexHtml)
		Do While _abcPdfDoc.Chainable(id)
			_abcPdfDoc.Page = _abcPdfDoc.AddPage()
			id = _abcPdfDoc.AddImageToChain(id)
		Loop
		_abcPdfDoc.Save("temp_abc_complex.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Résultats typiques

Méthode de travail Moyen Erreur StdDev Mémoire
IronPDF_SimpleHtml 245.3 ms 4.2 ms 3.8 ms 152 MB
ABCpdf_SimpleHtml 187.6 ms 3.1 ms 2.9 ms 98 MB
IronPDF_ComplexHtml 892.4 ms 12.3 ms 10.8 ms 201 MO
ABCpdf_ComplexHtml 743.2 ms 9.7 ms 8.6 ms 145 MB

Observations clés :

  • ABCpdf affiche des temps de conversion bruts plus rapides
  • IronPDF utilise plus de mémoire grâce au moteur Chrome complet
  • Les deux bibliothèques s'adaptent linéairement à la complexité du document
  • La surcharge d'IronPDF permet une meilleure précision de rendu

Comparaison des fonctionnalités avancées

Signatures numériques et sécurité

Mise en œuvre de la signature numérique IronPDF

using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;

public class SecurityFeatures
{
    public static void ApplyDigitalSignature()
    {
        // Load existing PDF
        var pdf = PdfDocument.FromFile("unsigned-document.pdf");

        // Load certificate
        var cert = new X509Certificate2("certificate.pfx", "password");

        // Create signature
        var signature = new PdfSignature(cert)
        {
            // Visual signature appearance
            SignatureImage = new PdfSignature.SignatureImage
            {
                ImagePath = "signature.png",
                Width = 200,
                Height = 100
            },

            // Signature position
            PageIndex = 0,
            X = 400,
            Y = 100,

            // Signature details
            Reason = "Document approved",
            Location = "New York, NY",
            ContactInfo = "john.doe@company.com"
        };

        // Apply signature
        pdf.Sign(signature);

        // Additional security
        pdf.SecuritySettings = new SecuritySettings
        {
            AllowUserPrinting = true,
            AllowUserCopyPasteContent = false,
            AllowUserEditing = false,
            AllowUserFormData = true,
            OwnerPassword = "owner123",
            UserPassword = "user123",
            EncryptionLevel = EncryptionLevel.AES256
        };

        pdf.SaveAs("signed-secured.pdf");
    }
}
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;

public class SecurityFeatures
{
    public static void ApplyDigitalSignature()
    {
        // Load existing PDF
        var pdf = PdfDocument.FromFile("unsigned-document.pdf");

        // Load certificate
        var cert = new X509Certificate2("certificate.pfx", "password");

        // Create signature
        var signature = new PdfSignature(cert)
        {
            // Visual signature appearance
            SignatureImage = new PdfSignature.SignatureImage
            {
                ImagePath = "signature.png",
                Width = 200,
                Height = 100
            },

            // Signature position
            PageIndex = 0,
            X = 400,
            Y = 100,

            // Signature details
            Reason = "Document approved",
            Location = "New York, NY",
            ContactInfo = "john.doe@company.com"
        };

        // Apply signature
        pdf.Sign(signature);

        // Additional security
        pdf.SecuritySettings = new SecuritySettings
        {
            AllowUserPrinting = true,
            AllowUserCopyPasteContent = false,
            AllowUserEditing = false,
            AllowUserFormData = true,
            OwnerPassword = "owner123",
            UserPassword = "user123",
            EncryptionLevel = EncryptionLevel.AES256
        };

        pdf.SaveAs("signed-secured.pdf");
    }
}
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates

Public Class SecurityFeatures
	Public Shared Sub ApplyDigitalSignature()
		' Load existing PDF
		Dim pdf = PdfDocument.FromFile("unsigned-document.pdf")

		' Load certificate
		Dim cert = New X509Certificate2("certificate.pfx", "password")

		' Create signature
		Dim signature = New PdfSignature(cert) With {
			.SignatureImage = New PdfSignature.SignatureImage With {
				.ImagePath = "signature.png",
				.Width = 200,
				.Height = 100
			},
			.PageIndex = 0,
			.X = 400,
			.Y = 100,
			.Reason = "Document approved",
			.Location = "New York, NY",
			.ContactInfo = "john.doe@company.com"
		}

		' Apply signature
		pdf.Sign(signature)

		' Additional security
		pdf.SecuritySettings = New SecuritySettings With {
			.AllowUserPrinting = True,
			.AllowUserCopyPasteContent = False,
			.AllowUserEditing = False,
			.AllowUserFormData = True,
			.OwnerPassword = "owner123",
			.UserPassword = "user123",
			.EncryptionLevel = EncryptionLevel.AES256
		}

		pdf.SaveAs("signed-secured.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Mise en œuvre de la signature numérique d'ABCpdf

using WebSupergoo.ABCpdf13;
using WebSupergoo.ABCpdf13.Objects;

public class ABCpdfSecurity
{
    public static void SignDocument()
    {
        using (Doc theDoc = new Doc())
        {
            theDoc.Read("unsigned-document.pdf");

            // Create signature field
            Field signatureField = theDoc.Form.AddFieldSignature("AuthorSignature");
            signatureField.Page = 1;
            signatureField.Rect = "400 100 600 200";

            // Configure signature
            Signature theSig = signatureField.Sign();
            theSig.Reason = "Document approved";
            theSig.Location = "New York, NY";
            theSig.ContactInfo = "john.doe@company.com";

            // Load certificate
            theSig.LoadCertificate("certificate.pfx", "password");

            // Apply visual signature
            theSig.Visible = true;
            theSig.Image = theDoc.AddImageFile("signature.png");

            // Sign and save
            theDoc.Save("abcpdf-signed.pdf");
        }
    }
}
using WebSupergoo.ABCpdf13;
using WebSupergoo.ABCpdf13.Objects;

public class ABCpdfSecurity
{
    public static void SignDocument()
    {
        using (Doc theDoc = new Doc())
        {
            theDoc.Read("unsigned-document.pdf");

            // Create signature field
            Field signatureField = theDoc.Form.AddFieldSignature("AuthorSignature");
            signatureField.Page = 1;
            signatureField.Rect = "400 100 600 200";

            // Configure signature
            Signature theSig = signatureField.Sign();
            theSig.Reason = "Document approved";
            theSig.Location = "New York, NY";
            theSig.ContactInfo = "john.doe@company.com";

            // Load certificate
            theSig.LoadCertificate("certificate.pfx", "password");

            // Apply visual signature
            theSig.Visible = true;
            theSig.Image = theDoc.AddImageFile("signature.png");

            // Sign and save
            theDoc.Save("abcpdf-signed.pdf");
        }
    }
}
Imports WebSupergoo.ABCpdf13
Imports WebSupergoo.ABCpdf13.Objects

Public Class ABCpdfSecurity
	Public Shared Sub SignDocument()
		Using theDoc As New Doc()
			theDoc.Read("unsigned-document.pdf")

			' Create signature field
			Dim signatureField As Field = theDoc.Form.AddFieldSignature("AuthorSignature")
			signatureField.Page = 1
			signatureField.Rect = "400 100 600 200"

			' Configure signature
			Dim theSig As Signature = signatureField.Sign()
			theSig.Reason = "Document approved"
			theSig.Location = "New York, NY"
			theSig.ContactInfo = "john.doe@company.com"

			' Load certificate
			theSig.LoadCertificate("certificate.pfx", "password")

			' Apply visual signature
			theSig.Visible = True
			theSig.Image = theDoc.AddImageFile("signature.png")

			' Sign and save
			theDoc.Save("abcpdf-signed.pdf")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Traitement des formulaires et extraction de données

Gestion des formulaires IronPDF

public class FormHandling
{
    public static void WorkWithForms()
    {
        // Create PDF with form fields from HTML
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

        string formHtml = @"
        <form>
            <label>Name: <input type='text' name='fullname' required></label><br>
            <label>Email: <input type='email' name='email' required></label><br>
            <label>Subscribe: <input type='checkbox' name='subscribe' value='yes'></label><br>
            <label>Country: 
                <select name='country'>
                    <option>USA</option>
                    <option>Canada</option>
                    <option>UK</option>
                </select>
            </label><br>
            <button type='submit'>Submit</button>
        </form>";

        var pdf = renderer.RenderHtmlAsPdf(formHtml);

        // Fill form programmatically
        pdf.Form.Fields["fullname"].Value = "John Doe";
        pdf.Form.Fields["email"].Value = "john@example.com";
        pdf.Form.Fields["subscribe"].Value = "yes";
        pdf.Form.Fields["country"].Value = "USA";

        // Extract form data
        foreach (var field in pdf.Form.Fields)
        {
            Console.WriteLine($"{field.Name}: {field.Value}");
        }

        // Flatten form (make non-editable)
        pdf.Form.Flatten();
        pdf.SaveAs("filled-form.pdf");
    }
}
public class FormHandling
{
    public static void WorkWithForms()
    {
        // Create PDF with form fields from HTML
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

        string formHtml = @"
        <form>
            <label>Name: <input type='text' name='fullname' required></label><br>
            <label>Email: <input type='email' name='email' required></label><br>
            <label>Subscribe: <input type='checkbox' name='subscribe' value='yes'></label><br>
            <label>Country: 
                <select name='country'>
                    <option>USA</option>
                    <option>Canada</option>
                    <option>UK</option>
                </select>
            </label><br>
            <button type='submit'>Submit</button>
        </form>";

        var pdf = renderer.RenderHtmlAsPdf(formHtml);

        // Fill form programmatically
        pdf.Form.Fields["fullname"].Value = "John Doe";
        pdf.Form.Fields["email"].Value = "john@example.com";
        pdf.Form.Fields["subscribe"].Value = "yes";
        pdf.Form.Fields["country"].Value = "USA";

        // Extract form data
        foreach (var field in pdf.Form.Fields)
        {
            Console.WriteLine($"{field.Name}: {field.Value}");
        }

        // Flatten form (make non-editable)
        pdf.Form.Flatten();
        pdf.SaveAs("filled-form.pdf");
    }
}
Public Class FormHandling
	Public Shared Sub WorkWithForms()
		' Create PDF with form fields from HTML
		Dim renderer = New ChromePdfRenderer()
		renderer.RenderingOptions.CreatePdfFormsFromHtml = True

		Dim formHtml As String = "
        <form>
            <label>Name: <input type='text' name='fullname' required></label><br>
            <label>Email: <input type='email' name='email' required></label><br>
            <label>Subscribe: <input type='checkbox' name='subscribe' value='yes'></label><br>
            <label>Country: 
                <select name='country'>
                    <option>USA</option>
                    <option>Canada</option>
                    <option>UK</option>
                </select>
            </label><br>
            <button type='submit'>Submit</button>
        </form>"

		Dim pdf = renderer.RenderHtmlAsPdf(formHtml)

		' Fill form programmatically
		pdf.Form.Fields("fullname").Value = "John Doe"
		pdf.Form.Fields("email").Value = "john@example.com"
		pdf.Form.Fields("subscribe").Value = "yes"
		pdf.Form.Fields("country").Value = "USA"

		' Extract form data
		For Each field In pdf.Form.Fields
			Console.WriteLine($"{field.Name}: {field.Value}")
		Next field

		' Flatten form (make non-editable)
		pdf.Form.Flatten()
		pdf.SaveAs("filled-form.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Traitement par lots et optimisation

Traitement par lots d'IronPDF

using System.Threading.Tasks;
using System.Collections.Concurrent;

public class BatchProcessing
{
    public static async Task ProcessMultipleDocumentsAsync(List<string> htmlFiles)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;

        // Use concurrent processing
        var pdfResults = new ConcurrentBag<(string filename, byte[] data)>();

        await Parallel.ForEachAsync(htmlFiles, async (htmlFile, ct) =>
        {
            try
            {
                var html = await File.ReadAllTextAsync(htmlFile);
                var pdf = await renderer.RenderHtmlAsPdfAsync(html);

                // Optimize each PDF
                pdf.CompressImages(70);

                var filename = Path.GetFileNameWithoutExtension(htmlFile) + ".pdf";
                var data = pdf.BinaryData;

                pdfResults.Add((filename, data));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing {htmlFile}: {ex.Message}");
            }
        });

        // Merge all PDFs into one
        var finalPdf = new PdfDocument();
        foreach (var (filename, data) in pdfResults.OrderBy(x => x.filename))
        {
            var pdf = new PdfDocument(data);
            finalPdf.AppendPdf(pdf);
        }

        finalPdf.SaveAs("batch-processed.pdf");
    }
}
using System.Threading.Tasks;
using System.Collections.Concurrent;

public class BatchProcessing
{
    public static async Task ProcessMultipleDocumentsAsync(List<string> htmlFiles)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;

        // Use concurrent processing
        var pdfResults = new ConcurrentBag<(string filename, byte[] data)>();

        await Parallel.ForEachAsync(htmlFiles, async (htmlFile, ct) =>
        {
            try
            {
                var html = await File.ReadAllTextAsync(htmlFile);
                var pdf = await renderer.RenderHtmlAsPdfAsync(html);

                // Optimize each PDF
                pdf.CompressImages(70);

                var filename = Path.GetFileNameWithoutExtension(htmlFile) + ".pdf";
                var data = pdf.BinaryData;

                pdfResults.Add((filename, data));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing {htmlFile}: {ex.Message}");
            }
        });

        // Merge all PDFs into one
        var finalPdf = new PdfDocument();
        foreach (var (filename, data) in pdfResults.OrderBy(x => x.filename))
        {
            var pdf = new PdfDocument(data);
            finalPdf.AppendPdf(pdf);
        }

        finalPdf.SaveAs("batch-processed.pdf");
    }
}
Imports System.Threading.Tasks
Imports System.Collections.Concurrent

Public Class BatchProcessing
	Public Shared Async Function ProcessMultipleDocumentsAsync(ByVal htmlFiles As List(Of String)) As Task
		Dim renderer = New ChromePdfRenderer()
		renderer.RenderingOptions.PaperSize = PdfPaperSize.A4

		' Use concurrent processing
		Dim pdfResults = New ConcurrentBag(Of (filename As String, data As Byte()))()

		Await Parallel.ForEachAsync(htmlFiles, Async Sub(htmlFile, ct)
			Try
				Dim html = Await File.ReadAllTextAsync(htmlFile)
				Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)

				' Optimize each PDF
				pdf.CompressImages(70)

				Dim filename = Path.GetFileNameWithoutExtension(htmlFile) & ".pdf"
				Dim data = pdf.BinaryData

				pdfResults.Add((filename, data))
			Catch ex As Exception
				Console.WriteLine($"Error processing {htmlFile}: {ex.Message}")
			End Try
		End Sub)

		' Merge all PDFs into one
		Dim finalPdf = New PdfDocument()
		foreach var(filename, data) In pdfResults.OrderBy(Function(x) x.filename)
			Dim pdf = New PdfDocument(data)
			finalPdf.AppendPdf(pdf)
		Next 

		finalPdf.SaveAs("batch-processed.pdf")
	End Function
End Class
$vbLabelText   $csharpLabel

Scénarios de cas d'utilisation réels

Quelle bibliothèque convient le mieux à votre projet ? #### Choisissez IronPDF quand : 1. **Construire des applications cloud-natives** - Prise en charge native de Docker avec une configuration minimale - Compatibilité avec Azure Functions et AWS Lambda - Comportement cohérent sur toutes les plateformes cloud 2. **Requiring Pixel-Perfect HTML Rendering** (Exigence d'un rendu HTML parfait) - Mises en page CSS complexes (Grid, Flexbox) - Applications à page unique à forte composante JavaScript - Exigences en matière de polices Web 3. **Développement de solutions multiplateformes** - Applications ciblant Windows, Linux et macOS - Architecture microservices - Déploiements basés sur des conteneurs 4. **Prioriser l'expérience des développeurs** - Besoins en matière de prototypage rapide - Petites équipes de développement - Expertise limitée en matière de PDF #### Choisissez ABCpdf quand: 1. **Travailler avec des systèmes hérités** - Environnements Windows uniquement - Implémentations existantes d'ABCpdf - Exigences en matière de contenu compatible avec IE 2. **Demande de moteurs de rendu spécifiques** - Test sur différents navigateurs - Optimisations spécifiques aux moteurs - Prise en charge des navigateurs existants 3. **Manipulation avancée des PDF** - Accès de bas niveau aux objets PDF - Opérateurs PDF personnalisés - Scénarios complexes de fusion de documents 4. **Projets à budget limité** - Prix d'entrée plus bas - Licences pour développeur unique - compatibilité avec les environnements 32 bits ## Dépannage des problèmes courants ### Questions et solutions communes à IronPDF ```csharp public class IronPdfTroubleshooting { // Issue: Fonts not rendering correctly public static void FixFontIssues() { var renderer = new ChromePdfRenderer(); // Solution 1: Wait for fonts to load renderer.RenderingOptions.WaitFor.RenderDelay(1000); // Solution 2: Use system fonts fallback renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print; } // Issue: JavaScript not executing public static void FixJavaScriptIssues() { var renderer = new ChromePdfRenderer(); // Enable JavaScript and wait for execution renderer.RenderingOptions.EnableJavaScript = true; renderer.RenderingOptions.WaitFor.JavaScriptFinishDelay = 2000; renderer.RenderingOptions.WaitFor.AllowedExecutionTime = 30000; } // Issue: Mémoireusage in Docker public static void OptimizeForDocker() { var renderer = new ChromePdfRenderer(); // Use single-threaded mode for containers IronPdf.Installation.SingleThreaded = true; // Reduce memory footprint renderer.RenderingOptions.ViewPortWidth = 1024; renderer.RenderingOptions.EnableGrayscale = true; } } ``` ### ABCpdf Problèmes courants et solutions ```csharp public class ABCpdfTroubleshooting { // Issue: Page breaks in wrong places public static void FixPageBreaks() { using (Doc theDoc = new Doc()) { // Use HTML page break controls theDoc.HtmlOptions.BreakZoneSize = 100; // pixels theDoc.HtmlOptions.UseScript = true; string html = @"
Keep this content together
New page content
"; theDoc.AddImageHtml(html); theDoc.Save("fixed-breaks.pdf"); } } // Issue: Images not loading public static void FixImageLoading() { using (Doc theDoc = new Doc()) { // Set timeout and authentication theDoc.HtmlOptions.Timeout = 60000; // 60 seconds theDoc.HtmlOptions.RetryCount = 3; // For local images, set base directory theDoc.HtmlOptions.BaseUrl = @"file:///C:/Images/"; theDoc.AddImageHtml("Logo related to Scénarios de cas d'utilisation réels"); theDoc.Save("with-images.pdf"); } } } ``` ## Guide de migration : Passer d'une bibliothèque à l'autre ### Migration d'ABCpdf vers IronPDF ```csharp public class MigrationHelper { // ABCpdf code public void OldABCpdfMethod() { Doc theDoc = new Doc(); theDoc.AddImageUrl("https://example.com"); theDoc.Save("output.pdf"); theDoc.Dispose(); } // Equivalent IronPDF code public void NewIronPdfMethod() { var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderUrlAsPdf("https://example.com"); pdf.SaveAs("output.pdf"); } // Migration wrapper for gradual transition public class PdfWrapper { private bool _useIronPdf; public PdfWrapper(bool useIronPdf = true) { _useIronPdf = useIronPdf; } public void ConvertUrlToPdf(string url, string outputPath) { if (_useIronPdf) { var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderUrlAsPdf(url); pdf.SaveAs(outputPath); } else { using (var doc = new Doc()) { doc.AddImageUrl(url); doc.Save(outputPath); } } } } } ``` ## Licences et coût total de possession ### Calculer le retour sur investissement de votre projet Lorsque vous évaluez des bibliothèques PDF, tenez compte du coût total au-delà du prix de la licence : #### Analyse des coûts d'IronPDF - **Gain de temps de développement** : mise en œuvre 50-70% plus rapide - **Coûts d'assistance** : Assistance technique 24/5 incluse - **Maintenance** : API unifiée pour toutes les plateformes - **Échelonnabilité** : une seule licence couvre plusieurs déploiements #### Analyse des coûts d'ABCpdf - **Coût initial** : Prix d'entrée moins élevé - **Coûts cachés** : - Licence 64 bits séparée - Exigences en matière de moteurs multiples - Tests spécifiques aux plates-formes - Coûts d'assistance supplémentaires ### Calculateur de comparaison de licences ```csharp public class LicenseCostCalculator { public static void CalculateTotalCost() { // Scenario: 5-developer team, 3-year project // IronPDF Professional var ironPdfCost = new { License = 2999, // 10 developers, 10 projects Support = 0, // Included Training = 500, // Minimal due to simple API ThreeYearTotal = 3499 }; // ABCpdf equivalent setup var abcPdfCost = new { StandardLicenses = 329 * 5, // 5 developers ProfessionalUpgrade = 150 * 5, // 64-bit support RedistributionLicense = 4790, // Enterprise Support = 399 * 3, // Annual support Training = 2000, // Complex API training ThreeYearTotal = 1645 + 750 + 4790 + 1197 + 2000 }; Console.WriteLine($"IronPDF 3-year TCO: ${ironPdfCost.ThreeYearTotal:N0}"); Console.WriteLine($"ABCpdf 3-year TCO: ${abcPdfCost.ThreeYearTotal:N0}"); Console.WriteLine($"Savings with IronPDF: ${abcPdfCost.ThreeYearTotal - ironPdfCost.ThreeYearTotal:N0}"); } } ``` ## Conclusion Après une analyse approfondie des deux bibliothèques, plusieurs éléments clés de différenciation sont apparus : **IronPDF excelle dans:** - Prise en charge des technologies web modernes avec un rendu basé sur Chrome - Cohérence multiplateforme et déploiements cloud-native - Productivité des développeurs grâce à des API intuitives - Assistance et documentation complètes - Une meilleure valeur à long terme pour les équipes en pleine croissance **ABCpdf offre des avantages en :** - Coût initial réduit pour les projets de base sous Windows uniquement - Plusieurs options de moteur de rendu - Compatibilité avec les systèmes existants - Une empreinte mémoire réduite pour les documents simples IronPDF offre une solution unique à tous les problèmes liés aux PDF. Lorsque vous achetez IronPDF, vous obtenez toutes les conversions dans une seule bibliothèque, plus les tâches liées aux documents PDF uniquement, ne nécessitant aucune dépendance supplémentaire. Cette approche consolidée, associée à une qualité de rendu supérieure et à une prise en charge multiplateforme, fait d'IronPDF le choix recommandé pour la plupart des applications .NET modernes. Pour les équipes qui privilégient un développement rapide, des résultats cohérents sur toutes les plateformes et une maintenabilité à long terme, le coût initial plus élevé d'IronPDF est compensé par une réduction du temps de développement, une meilleure assistance et une diminution des problèmes de compatibilité. ## Démarrer avec IronPDF Prêt à découvrir la différence ? [Démarrez votre essai gratuit](trial-license) dès aujourd'hui : ```csharp // Get started in minutes // Install-Package IronPdf // Your first PDF in 3 lines var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf("

Hello World

"); pdf.SaveAs("my-first-pdf.pdf"); ``` Visit our comprehensive [documentation](https://ironpdf.com/docs/), explore [code examples](/examples/using-html-to-create-a-pdf/), or chat with our engineering team for personalized guidance on your PDF generation needs. [{i :(ABCpdf est une marque déposée de son propriétaire respectif. Ce site n'est pas affilié, endossé ou sponsorisé par ABCpdf. Tous les noms de produits, logos et marques appartiennent à leurs propriétaires respectifs. Les comparaisons sont faites à titre d'information uniquement et reflètent les informations publiquement disponibles au moment de la rédaction.)}]

Questions Fréquemment Posées

Quelles sont les principales différences entre IronPDF et ABCpdf en termes de moteurs de rendu ?

IronPDF utilise un moteur de rendu basé sur Chrome, offrant un rendu impeccable et un support complet pour CSS3 et JavaScript, ce qui le rend idéal pour le rendu des technologies web modernes. En revanche, ABCpdf offre plusieurs moteurs de rendu comme Chrome, Firefox ou IE, permettant une flexibilité mais nécessitant plus de tests et de configuration.

Comment se compare la qualité de conversion HTML en PDF d'IronPDF et d'ABCpdf ?

IronPDF excelle en précision de rendu grâce à son moteur basé sur Chrome, qui correspond à la sortie des navigateurs modernes. ABCpdf, bien que légèrement plus rapide, pourrait ne pas offrir le même niveau de précision avec un contenu web moderne complexe.

Quelles sont les différences de compatibilité entre IronPDF et ABCpdf ?

IronPDF offre un support natif multiplateforme, fonctionnant sur Windows, Linux, macOS et les conteneurs Docker. ABCpdf cible principalement les environnements Windows, ce qui peut limiter son utilisation dans des configurations de développement variées.

Quelle bibliothèque offre une meilleure valeur à long terme pour les applications .NET, IronPDF ou ABCpdf ?

Bien qu'ABCpdf ait un prix d'entrée inférieur, le support complet d'IronPDF, son architecture moderne et son API unifiée offrent une valeur à long terme, notamment pour les applications .NET contemporaines nécessitant une maintenance et des mises à jour continues.

Comment IronPDF compare-t-il son modèle de licence avec celui d'ABCpdf pour une utilisation en entreprise ?

Les licences d'IronPDF commencent à partir de 749 dollars, tandis qu'ABCpdf offre un prix d'entrée inférieur à 329 dollars. Cependant, les calculs de coût total de possession favorisent IronPDF pour son support étendu et ses mises à jour, en faisant un choix économique pour une utilisation en entreprise.

Quelles stratégies de migration existent pour passer d'ABCpdf à IronPDF ?

Pour migrer d'ABCpdf à IronPDF, les développeurs peuvent utiliser la documentation API complète et les ressources de support d'IronPDF. Ils devraient mapper les fonctionnalités actuelles aux méthodes d'IronPDF, tester minutieusement la sortie pour assurer des résultats cohérents.

IronPDF peut-il gérer du contenu HTML dynamique avec JavaScript ?

Oui, IronPDF peut exécuter JavaScript avant le rendu, prenant en charge le contenu dynamique, les appels AJAX et les frameworks modernes. Il permet des temps d'attente et des délais de rendu configurables pour garantir le traitement complet des éléments dynamiques.

Quelle est la méthode recommandée pour résoudre les problèmes de rendu lors de l'utilisation d'IronPDF ?

Pour résoudre les problèmes de rendu avec IronPDF, assurez-vous d'abord que les fonctionnalités CSS sont supportées par le moteur Chrome. Utilisez les requêtes média d'impression pour les styles spécifiques aux PDF, validez le CSS avec les outils développeur du navigateur, et testez avec du HTML simplifié pour isoler les problèmes.

Jacob Mellor, Directeur technique @ Team Iron
Directeur technique

Jacob Mellor est directeur technique chez Iron Software et un ingénieur visionnaire pionnier dans la technologie des PDF en C#. En tant que développeur original derrière la base de code principale d'Iron Software, il a façonné l'architecture du produit de l'entreprise depuis sa création, ...

Lire la suite