UTILISATION DE L'IRON SUITE

HTML to PDF en C# pour les développeurs .NET (Le guide ultime)

décembre 15, 2024
Partager:

Introduction

Dans le monde actuel axé sur le web, la capacité de convertir du contenu HTML en documents PDF est une fonctionnalité cruciale pour de nombreuses applications. Que ce soit pour générer des rapports, des factures ou enregistrer des pages web pour une utilisation hors ligne, la conversion de HTML en PDF joue un rôle essentiel dans l'optimisation des flux de travail et l'amélioration des expériences utilisateurs. Pour les développeurs .NET, choisir le bon outil pour gérer cette conversion peut avoir un impact significatif sur l'efficacité et la qualité de leurs applications.

Dans cet article, nous explorerons comment convertir du HTML en PDF en C# en couvrant les sujets suivants :

  1. Pourquoi comparer les outils HTML en PDF ?

  2. IronPDF : Conversion HTML vers PDF

  3. Aspose : Conversion HTML en PDF

  4. iText7 : Conversion HTML en PDF

  5. wkhtmltopdf : Conversion HTML en PDF

  6. PuppeteerSharp : Conversion HTML en PDF

  7. Conclusion Pourquoi choisir IronPDF ?

    À la fin, vous comprendrez pourquoi IronPDF se distingue comme un convertisseur HTML en PDF efficace et convivial pour les développeurs.

Pourquoi comparer les outils HTML en PDF ?

Choisir l'outil de conversion de HTML en PDF approprié est essentiel pour garantir que votre application réponde aux exigences de performance, de qualité et de coût. Avec de nombreuses options disponibles, offrant chacune des caractéristiques et des capacités différentes, une comparaison approfondie aide à prendre une décision éclairée. Voici les principaux critères d'évaluation à considérer :

  • Complexité d'intégration : Facilité avec laquelle la bibliothèque s'intègre à vos projets .NET existants.
  • Simplicité du code : La facilité d'écriture et de maintenance du code en utilisant la bibliothèque.
  • Précision de rendu : La capacité de restituer avec précision le HTML, le CSS et le JavaScript complexes.
  • Performance à grande échelle : Efficacité de la bibliothèque sous forte charge et lors de la génération de PDF à grande échelle.
  • Licences et Rentabilité : Les modèles de tarification et les conditions de licence adaptés au budget de votre projet.

    En évaluant ces facteurs, vous pouvez choisir un outil qui non seulement correspond à vos exigences techniques mais qui s'aligne également avec les contraintes financières de votre projet.

IronPDF : Conversion HTML en PDF

HTML en PDF en C# pour les développeurs .NET (Le guide ultime) : Figure 1

IronPDF est une bibliothèque .NET complète pour convertir du HTML en PDF. Il prend en charge les chaînes HTML, les fichiers HTML locaux et les URL, ce qui le rend polyvalent pour un large éventail de cas d'utilisation. Voici comment IronPDF gère chaque scénario :

Chaîne HTML vers PDF

Convertir du HTML d'une chaîne en PDF est simple avec IronPDF. Cette approche est idéale pour la génération de contenu dynamique ou de petits extraits HTML.

Exemple :

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
		PDF.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

HTML vers PDF en C# pour les développeurs .NET (Le guide ultime) : Figure 2

Explication :

  1. ChromePdfRenderer : La classe ChromePdfRenderer est l'outil principal pour convertir le HTML en PDF dans IronPDF. Il est préconfiguré pour gérer la plupart des cas d'utilisation avec un minimum de configuration.

  2. RenderHtmlAsPdf : Cette méthode prend une chaîne HTML en entrée et génère un document PDF.

  3. SaveAs : Le PDF généré est enregistré à l'emplacement spécifié (output.pdf).

Fichier HTML local en PDF

Pour les applications qui ont besoin de convertir un fichier HTML local (avec des ressources externes comme CSS ou JavaScript), IronPDF simplifie la tâche.

Exemple :

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("template.html")
		pdf.SaveAs("report.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Fichier HTML d'entrée

HTML to PDF en C# pour développeurs .NET (Le guide ultime) : Figure 3

Sortie

HTML vers PDF en C# pour les développeurs .NET (Le guide ultime) : Figure 4

Explication :

  • RenderHtmlFileAsPdf : Prend un fichier HTML local et le convertit en PDF.
  • Gère automatiquement les ressources liées, telles que les fichiers CSS et JavaScript externes.

URL vers PDF

IronPDF est particulièrement puissant lorsqu'il s'agit de convertir du contenu web dynamique à partir de URLs, y compris les pages utilisant JavaScript.

Exemple :

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com")
		pdf.SaveAs("url-to-pdf.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

HTML vers PDF en C# pour .NET Developers (Le guide ultime) : Figure 5

Explication :

  • RenderUrlAsPdf : Récupère le contenu de l'URL, y compris les éléments rendus par JavaScript, et le convertit en PDF.

Aspose : Conversion HTML en PDF

HTML vers PDF en C# pour les développeurs .NET (Le guide ultime) : Figure 6

Aspose.PDF est une autre bibliothèque puissante pour la manipulation de PDF, avec la prise en charge de la conversion de HTML en PDF. Voyons comment Aspose gère chaque scénario de conversion :

Chaîne HTML vers PDF

Aspose nécessite un peu plus de configuration lors de la conversion de chaînes HTML par rapport à IronPDF.

Exemple :

using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
Imports Aspose.Html
Private doc As New Document()
Private page As Page = doc.getPages().add()
Private htmlFragment As New HtmlFragment("<h1>HTML String</h1>")
page.getParagraphs().add(htmlFragment)
doc.save(dataDir & "HTMLStringUsingDOM.pdf")
$vbLabelText   $csharpLabel

Explication :

  • Document doc : Crée un nouveau document pour enregistrer la chaîne HTML convertie.
  • Page page : Cette ligne ajoute une nouvelle page au document vide que nous avons créé.
  • HtmlFragment htmlFragment : Voici la chaîne HTML que nous convertissons.
  • page.getParagraphs().add(htmlFragment) : Ajoutez le HTML au document
  • doc.save : Enregistre le document avec le contenu HTML en tant que document PDF.

Fichier HTML local en PDF

Aspose gère également la conversion de fichiers HTML locaux en PDF, mais cela nécessite plus de configuration qu'IronPDF.

Exemple :

using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
    using var document = new HTMLDocument("document.html");
    var options = new PdfSaveOptions();
    Converter.ConvertHTML(document, options, "output.pdf");
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
    using var document = new HTMLDocument("document.html");
    var options = new PdfSaveOptions();
    Converter.ConvertHTML(document, options, "output.pdf");
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
	Private document = New HTMLDocument("document.html")
	Private options = New PdfSaveOptions()
	Converter.ConvertHTML(document, options, "output.pdf")
$vbLabelText   $csharpLabel

Explication :

  • using var document = new HTMLDocument("document.html") : Charge le fichier HTML.
  • var options : Crée un nouvel objet PdfSaveOptions
  • Converter.ConvertHTML() : Convertit le HTML en PDF.

URL vers PDF

Aspose offre des fonctionnalités similaires pour les URL mais nécessite une configuration supplémentaire.

Exemple :

using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
Imports System.IO
Imports System
Imports System.Net
Imports Aspose.Pdf
Private dataDir As String = "YOUR DOCUMENT DIRECTORY" ' Replace with your path
Private request As WebRequest = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Dim stream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer))
Dim options As New HtmlLoadOptions("https://en.wikipedia.org/wiki/")
Dim pdfDocument As New Document(stream, options)
pdfDocument.Save(dataDir & "WebPageToPDF_out.pdf")
$vbLabelText   $csharpLabel

Explication :

  • La variable dataDir contient le répertoire où le PDF généré sera enregistré.
  • Une WebRequest est créée pour accéder à l'URL de la page principale de Wikipedia, et les informations d'identification par défaut sont utilisées pour la requête.
  • La méthode GetResponse() envoie la requête et récupère la réponse sous forme de HttpWebResponse.
  • Un flux est obtenu à partir de la réponse, et un StreamReader lit l'intégralité du contenu HTML de la page dans la chaîne responseFromServer.
  • Le contenu HTML de responseFromServer est converti en un tableau d'octets puis chargé dans un MemoryStream.
  • HtmlLoadOptions est utilisé pour spécifier l'URL de base pour les liens relatifs et d'autres paramètres.
  • Un Aspose.Pdf.Document est créé à partir du flux de mémoire contenant le HTML, et le document est enregistré au format PDF dans le répertoire spécifié.

iText7 : Conversion HTML en PDF

HTML à PDF en C# pour les développeurs .NET (Le guide ultime) : Figure 7

iText7 est une bibliothèque PDF complète qui prend également en charge la conversion de HTML en PDF. Voici comment iText7 fonctionne dans différents scénarios :

Chaîne HTML vers PDF

iText7 utilise sa classe htmlConverter pour convertir une chaîne HTML en format PDF.

Exemple :

public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
Public Shared DEST As String = String.Format("{0}test-03.pdf", TARGET)
Private html = "<h1>Hello World</h1>"
HtmlConverter.ConvertToPdf(html, New FileStream(dest, FileMode.Create))
$vbLabelText   $csharpLabel

Fichier HTML local en PDF

iText7 peut convertir des types de fichiers HTML en PDF en utilisant la classe HtmlConverter.ConvertToPdf.

Exemple :

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("template.html", New FileStream("html-file-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
$vbLabelText   $csharpLabel

Explication :

  • HtmlConverter : Convertit un fichier HTML directement en PDF.

URL vers PDF

iText7 prend également en charge la conversion de contenu à partir d'URL.

Exemple :

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("https://example.com", New FileStream("url-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
$vbLabelText   $csharpLabel

Explication :

  • HtmlConverter : Gère le contenu de l'URL et le convertit en PDF.

wkhtmltopdf : Conversion HTML en PDF

HTML en PDF en C# pour développeurs .NET (Le guide ultime) : Figure 8

wkhtmltopdf est un outil en ligne de commande qui convertit les fichiers HTML en PDF en utilisant le moteur de rendu Webkit. Voici comment cela fonctionne pour différents scénarios :

Chaîne HTML vers PDF

wkhtmltopdf nécessite de convertir les chaînes HTML en les écrivant d'abord dans un fichier.

Exemple :

using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.IO
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' HTML string to be converted to PDF
		Dim html As String = "<html><body><h1>Hello, World!</h1></body></html>"
		' Write HTML string to temporary file
		Dim tempHtmlFile As String = Path.Combine(Path.GetTempPath(), "temp.html")
		File.WriteAllText(tempHtmlFile, html)
		' Set output PDF path
		Dim outputPdfFile As String = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf")
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{tempHtmlFile}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		' Clean up the temporary HTML file
		File.Delete(tempHtmlFile)
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Explication :

  • wkhtmltopdf nécessite un fichier d'entrée, nous écrivons donc d'abord la chaîne HTML dans un fichier temporaire (temp.html).
  • Nous utilisons ensuite la classe Process pour exécuter la commande wkhtmltopdf, en passant le chemin du fichier HTML temporaire et le chemin de sortie souhaité du PDF en tant qu'arguments.
  • Après la conversion, nous supprimons le fichier HTML temporaire pour nettoyer.

Fichier HTML local en PDF

Pour convertir un fichier HTML local en PDF en utilisant wkhtmltopdf, vous pouvez pointer directement vers le chemin du fichier HTML.

Exemple :

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\template.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\template.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Path to the local HTML file
		Dim htmlFilePath As String = "C:\path\to\your\template.html"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\html-file-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{htmlFilePath}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Explication :

  • Cet exemple fournit simplement le chemin vers le fichier HTML local (template.html) et le chemin de sortie pour le PDF.
  • wkhtmltopdf gère directement les fichiers locaux, rendant la commande simple.

URL vers PDF

Convertir une URL en PDF est facile avec wkhtmltopdf. Il suffit de passer l'URL directement à la commande.

Exemple :

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://example.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://example.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' URL to be converted to PDF
		Dim url As String = "https://example.com"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\url-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{url}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Explication :

  • Dans cet exemple, wkhtmltopdf accepte directement les URL en tant qu'entrée.
  • L'URL est passée comme argument à wkhtmltopdf, et le résultat est enregistré sous forme de PDF dans le chemin spécifié

PuppeteerSharp : Conversion HTML en PDF

HTML en PDF en C# pour les développeurs .NET (Le guide ultime) : Figure 9

PuppeteerSharp est un outil puissant pour automatiser Chrome ou Chromium sans tête, souvent utilisé pour le web scraping ou le rendu de pages web complexes. Voici des exemples d'utilisation de PuppeteerSharp pour convertir du HTML en PDF.

Chaîne HTML vers PDF

Puppeteer est conçu pour le rendu de pages complètes, donc convertir une chaîne HTML nécessite de l'écrire dans un fichier ou de la rendre directement dans un navigateur.

Exemple :

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>"
		Await page.SetContentAsync(htmlContent)
		' Save the page as a PDF
		Await page.PdfAsync("html-string-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

Explication :

  • Puppeteer.LaunchAsync : Lance une nouvelle instance de Chromium en mode sans tête.
  • page.SetContentAsync : Charge la chaîne HTML dans la page du navigateur.
  • page.PdfAsync : Convertit le HTML chargé en PDF et l'enregistre dans un fichier.

Fichier HTML local en PDF

Pour convertir un fichier HTML local en PDF en utilisant PuppeteerSharp, vous pouvez charger le fichier dans un navigateur sans tête et générer le PDF.

Exemple :

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");
        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");
        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		' Load the local HTML file
		Await page.GoToAsync("file:///path/to/your/template.html")
		' Save the page as a PDF
		Await page.PdfAsync("html-file-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

Explication :

  • page.GoToAsync : Charge le fichier HTML local (assurez-vous d’utiliser le chemin [file://]() correct).
  • page.PdfAsync : Convertit le contenu du fichier HTML local en PDF.

URL vers PDF

La conversion d'une URL en PDF est l'une des fonctionnalités principales de PuppeteerSharp, car il peut gérer des pages complexes avec JavaScript.

Exemple :

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Navigate to the URL
        await page.GoToAsync("https://example.com");
        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Navigate to the URL
        await page.GoToAsync("https://example.com");
        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		' Navigate to the URL
		Await page.GoToAsync("https://example.com")
		' Save the page as a PDF
		Await page.PdfAsync("url-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

Explication :

  • page.GoToAsync : Navigue vers l'URL spécifiée.
  • page.PdfAsync : Convertit la page web à l'URL en un PDF et l'enregistre.

Pourquoi choisir IronPDF ?

IronPDF se démarque par sa facilité d'utilisation, sa flexibilité et son intégration transparente avec les applications .NET. Il est simple à mettre en œuvre, prend en charge le rendu HTML, CSS et JavaScript, et ne nécessite pas de configuration supplémentaire ni de dépendances externes. Au-delà de la conversion d'HTML en PDF, IronPDF offre une vaste gamme de fonctionnalités pour créer des documents PDF à partir de divers types de fichiers, éditer et ajouter à des documents PDF existants, ajouter un filigrane, la sécurité des fichiers PDF, et bien plus encore ! Pour voir plus de cette bibliothèque en action, assurez-vous de consulter les Guides pratiques qui démontrent chacune de ses fonctionnalités en action.

Conclusion

Lorsqu'il s'agit de convertir des fichiers HTML en PDF en C#, plusieurs outils puissants sont disponibles, chacun offrant des fonctionnalités et des capacités uniques. IronPDF, Aspose, iText7, wkhtmltopdf, et PuppeteerSharp offrent tous des solutions robustes pour transformer du contenu HTML en documents PDF de qualité professionnelle. Cependant, choisir le bon outil pour votre projet dépend de facteurs tels que la facilité d'intégration, le support pour le contenu dynamique, la performance et la flexibilité.

HTML vers PDF en C# pour les développeurs .NET (Le Guide Ultime) : Figure 10

  • IronPDF se distingue par sa simplicité, son intégration directe avec .NET et sa capacité à gérer des HTML complexes, y compris des pages rendues en JavaScript. C'est parfait pour les développeurs recherchant une solution facile à utiliser avec une configuration minimale.
  • Aspose offre des fonctionnalités étendues de manipulation de PDF, mais ses capacités de conversion HTML en PDF nécessitent plus de configuration, notamment pour la gestion des fichiers locaux et des ressources externes.
  • iText7 offre une base solide pour ceux qui souhaitent créer des documents PDF, bien qu'il puisse nécessiter un codage supplémentaire pour convertir HTML en PDF, en particulier pour le contenu dynamique. C'est un excellent choix pour les projets nécessitant une manipulation personnalisée de PDF.
  • wkhtmltopdf est idéal pour la conversion HTML en PDF basique avec une interface en ligne de commande, mais il manque l'intégration et la flexibilité d'une bibliothèque complète .NET.
  • PuppeteerSharp, utilisant Google Chrome headless, est l'outil de référence pour rendre des pages web complexes et dynamiques et les convertir en PDF, en particulier lorsqu'il s'agit de contenu lourd en JavaScript.

    Pour la plupart des développeurs .NET à la recherche d'une solution tout-en-un et simple, IronPDF aujourd'hui pour découvrir ses fonctionnalités puissantes par vous-même.

    En fin de compte, le bon outil dépend de vos exigences spécifiques, mais avec les options discutées ici, vous êtes bien équipé pour trouver la solution parfaite pour votre projet.

< PRÉCÉDENT
HTML en PDF C# - Un guide complet avec IronPDF
SUIVANT >
Comment convertir CSHTML en PDF en C#