Test dans un environnement réel
Test en production sans filigrane.
Fonctionne partout où vous en avez besoin.
La fonction de génération de PDF en C# est essentielle pour de nombreuses applications modernes, allant de la création de rapports aux systèmes de facturation. Dans cet article, nous explorerons six manières populaires de générerPDF (EN ANGLAIS)fichiers en utilisant C#, en mettant en avant à la fois les bibliothèques basées sur le code, telles queIronPDF, et les API et outils en ligne. Que vous ayez besoin de générer un fichier PDF de manière dynamique dans une application web ou simplement de créer des fichiers PDF à partir de documents existants, ces outils vous couvrent.
Image cassée Ajouter depuis Pixabay, sélectionner depuis vos fichiers ou glisser-déposer une image ici.
IronPDFest une bibliothèque PDF .NET premium conçue pour les développeurs qui ont besoin de conversions de fichiers HTML en PDF de haute qualité. IronPDF utilise un moteur de rendu basé sur Chromium pour garantir des conversions précises, ce qui en fait un choix parfait pour les applications web souhaitant convertir des pages HTML ou des rapports basés sur le web en fichiers PDF en C#. L'outil est réputé pour sa gestion robuste des documents PDF existants et offre des fonctionnalités pour éditer, fusionner ou séparer des PDFs.
IronPDF s'intègre facilement dans les projets C# via NuGet Package Manager, et avec seulement quelques lignes de code, vous pouvez commencer à générer des documents PDF. C'est un outil polyvalent pour le contenu HTML dynamique et les sorties de fichiers PDF générées par le serveur.
using IronPdf;
class Program
{
static void Main()
{
string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
}
}
using IronPdf;
class Program
{
static void Main()
{
string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main()
Dim html As String = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>"
Dim renderer As New ChromePdfRenderer() ' Create an instance of ChromePdfRenderer
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html) ' Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf") ' Save the PDF to a specified file
End Sub
End Class
Importation d'Espace de Noms: using IronPdf; importe la bibliothèque IronPDF pour accéder à ses classes et méthodes.
Chaîne HTML : La variable HTML contient le contenu HTML que vous souhaitez convertir en PDF.
Instance de Rendu : new ChromePdfRenderer();** crée une instance de la classe HtmlToPdf, qui fournit des méthodes pour rendre le contenu HTML au format PDF.
Render PDF: PdfDocument PDF = renderer.RenderHtmlAsPdf(html);** convertit la chaîne HTML en document PDF.
iTextSharp est une bibliothèque PDF .NET bien établie qui offre une fonctionnalité étendue pour la création et l'édition de fichiers PDF. Il est largement utilisé dans des secteurs comme la finance et le juridique, où les documents doivent être personnalisés et sécurisés. iTextSharp vous permet de créer des fichiers PDF à partir de zéro, de remplir des formulaires et de modifier des fichiers PDF, offrant un contrôle étendu sur le contenu du document. Il est particulièrement utile pour les applications d'entreprise qui doivent générer des fichiers PDF avec des mises en page précises et des données dynamiques, telles que des factures ou des contrats.
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
public class PdfGenerator
{
public static Byte[] GeneratePdfFromFragment(string htmlFragment)
{
var html = string.Format(@"
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment);
return generate(html);
}
public static Byte[] GeneratePdfFromPage(string htmlPage)
{
return generate(htmlPage);
}
private static Byte[] generate (string html)
{
using (var memoryStream = new MemoryStream())
{
var pdfDocument = new Document(PageSize.LETTER);
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
pdfDocument.Open();
using (var fw = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
pdfDocument.Close();
fw.Close();
}
return memoryStream.ToArray();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
public class PdfGenerator
{
public static Byte[] GeneratePdfFromFragment(string htmlFragment)
{
var html = string.Format(@"
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment);
return generate(html);
}
public static Byte[] GeneratePdfFromPage(string htmlPage)
{
return generate(htmlPage);
}
private static Byte[] generate (string html)
{
using (var memoryStream = new MemoryStream())
{
var pdfDocument = new Document(PageSize.LETTER);
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
pdfDocument.Open();
using (var fw = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
pdfDocument.Close();
fw.Close();
}
return memoryStream.ToArray();
}
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Data.Entity.Core.Mapping
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Imports Voodoo
Namespace Helpers
Public Class PdfGenerator
Public Shared Function GeneratePdfFromFragment(ByVal htmlFragment As String) As Byte()
Dim html = String.Format("
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment)
Return generate(html)
End Function
Public Shared Function GeneratePdfFromPage(ByVal htmlPage As String) As Byte()
Return generate(htmlPage)
End Function
Private Shared Function generate(ByVal html As String) As Byte()
Using memoryStream As New MemoryStream()
Dim pdfDocument = New Document(PageSize.LETTER)
Dim pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream)
pdfDocument.Open()
Using fw = New StringReader(html)
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw)
pdfDocument.Close()
fw.Close()
End Using
Return memoryStream.ToArray()
End Using
End Function
End Class
End Namespace
GeneratePdfFromFragment : Prend un fragment HTML(comme un document HTML partiel) et le convertit en une structure HTML complète en l'encapsulant dans une structure de base
etmodèle. Il appelle ensuite la méthode interne generate.GeneratePdfFromPage : Accepte une page HTML complète et appelle directement la méthode de génération.
generate : Cette méthode gère la conversion de HTML en PDF.
Il initialise un MemoryStream pour contenir le PDF généré en mémoire.
4.
PDFSharp est une bibliothèque PDF .NET légère et open-source idéale pour les tâches de création de PDF de base. Si votre application nécessite uniquement des opérations simples comme l'ajout de texte, d'images ou de tableaux, PdfSharp est une option facile à utiliser pour générer des documents PDF en C#. Il manque de fonctionnalités avancées comme la conversion HTML en PDF, mais il se distingue par sa simplicité pour générer des fichiers PDF de petite à moyenne taille en C#.
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharp";
// Add a page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object to draw on the page
XGraphics gfx = XGraphics.FromPdfPage(page);
// Set a font to use for drawing text
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document to disk
document.Save("Generated.pdf");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharp";
// Add a page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object to draw on the page
XGraphics gfx = XGraphics.FromPdfPage(page);
// Set a font to use for drawing text
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document to disk
document.Save("Generated.pdf");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Friend Class Program
Shared Sub Main()
' Create a new PDF document
Dim document As New PdfDocument()
document.Info.Title = "Created with PdfSharp"
' Add a page to the document
Dim page As PdfPage = document.AddPage()
' Create an XGraphics object to draw on the page
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
' Set a font to use for drawing text
Dim font As New XFont("Verdana", 20, XFontStyle.Bold)
' Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.Center)
' Save the document to disk
document.Save("Generated.pdf")
End Sub
End Class
Syncfusion PDF Library est un outil performant et complet conçu pour les entreprises qui doivent travailler avec des PDF dans un large éventail d'applications. Il fait partie de la suite Syncfusion plus large, qui propose des bibliothèques pour une variété de formats et de plateformes. La bibliothèque PDF se distingue par son ensemble de fonctionnalités étendu qui va au-delà de la simple création de documents et permet une manipulation détaillée, y compris le remplissage de formulaires, les signatures numériques et la sécurité des documents.
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
static void Main()
{
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);
}
}
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
static void Main()
{
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);
}
}
Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing
Imports Syncfusion.Pdf.Graphics
Imports Syncfusion.Pdf.Grid
Friend Class Program
Shared Sub Main()
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Set the standard font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
'Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0, 0))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)
End Sub
End Class
PDFShift est un service basé sur le cloud conçu pour convertir des fichiers HTML en fichiers PDF. Il s'intègre parfaitement aux applications C# via son API, vous permettant de convertir des pages web HTML générées dynamiquement en PDF de qualité professionnelle. PDFShift est particulièrement utile pour les développeurs web qui souhaitent générer des documents PDF à la demande à partir de contenu HTML, tels que des factures ou des rapports. Étant donné que PDFShift fonctionne entièrement via son API REST, vous pouvez envoyer quelques lignes de HTML au service et recevoir en retour un fichier PDF téléchargeable. C'est une solution simple et évolutive pour la génération de fichiers PDF en ligne.
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Using client As New HttpClient()
Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>"
Dim content = New StringContent(htmlContent, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsync("https://api.pdfshift.io/v3/convert", content)
Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
End Using
End Function
End Class
DocRaptor est un autre service puissant de génération de PDF basé sur API qui convertit HTML et CSS en PDF de haute qualité. Il est connu pour son excellent rendu des documents HTML, en particulier pour la gestion des styles CSS complexes, des requêtes média et des polices Web. Cela fait de DocRaptor un excellent choix pour générer des documents professionnels tels que des rapports, des factures et des eBooks, directement à partir de modèles HTML.
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string apiKey = "YOUR_API_KEY";
string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string apiKey = "YOUR_API_KEY";
string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Using client As New HttpClient()
Dim apiKey As String = "YOUR_API_KEY"
Dim htmlContent As String = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>"
Dim jsonData As String = $"{{""test"": true, ""document_content"": ""{htmlContent}"", ""name"": ""Generated.pdf"", ""document_type"": ""pdf""}}"
Dim content = New StringContent(jsonData, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content)
Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
End Using
End Function
End Class
Si vous ne souhaitez pas programmer ou avez besoin d'une solution rapide pour générer des PDF, plusieurs outils en ligne vous permettent de créer des PDF rapidement et facilement. Voici quelques options notables :
Smallpdf est une plateforme en ligne offrant une variété d'outils liés aux PDF, y compris la capacité de créer des PDFs à partir d'un large éventail de formats de fichiers. Il est conçu pour les utilisateurs qui souhaitent une interface de glisser-déposer simple sans avoir besoin de coder. Smallpdf est largement utilisé pour des conversions rapides de fichiers, comme transformer des documents Word, des feuilles Excel ou des images en PDFs. Il offre également des outils pour fusionner, compresser et diviser des PDF, ce qui en fait un outil polyvalent pour les tâches PDF de base.
PDFescape est un éditeur PDF en ligne facile à utiliser qui permet aux utilisateurs de créer, modifier et visualiser des PDF sans avoir besoin d'installer de logiciel. C'est un excellent outil pour ceux qui ont besoin d'effectuer des modifications rapides sur des PDF, comme remplir des formulaires, ajouter des annotations textuelles ou insérer des images. PDFescape propose également des outils pour créer de nouveaux PDF à partir de zéro, ce qui en fait un choix flexible pour la création de documents de base.
PDF Candy est une suite d'outils PDF gratuits en ligne qui couvre un large éventail de tâches liées aux PDF, allant de la conversion de fichiers à l'édition. C'est un excellent choix pour les utilisateurs qui ont besoin d'effectuer rapidement des opérations PDF sans créer de compte ou installer de logiciel. PDF Candy prend en charge la conversion de divers types de fichiers, tels que des documents Word, des images et des fichiers texte, en PDF. Il offre également des outils pour fusionner, diviser et compresser des fichiers PDF.
Choisir le bon outil pour générer des fichiers PDF en C# dépend de vos besoins. Si vous devez générer des documents PDF à partir de contenu HTML, IronPDF et PDFShift sont d'excellentes options. iTextSharp et Syncfusion offrent des options de personnalisation étendues et un contrôle sur la structure des documents pour des projets plus complexes. Pour des solutions open-source plus simples, PDFsharp est un choix fiable pour modifier des fichiers PDF ou créer des PDF basiques. Enfin, pour les non-développeurs, Smallpdf, PDFescape et PDF Candy offrent des options simples et sans code pour travailler avec des fichiers PDF.
Pour ceux qui souhaitent essayerIronPDF, en faisant une excellente option pour les développeurs pour tester ses fonctionnalités de conversion HTML en PDF et de manipulation de PDF avant de s'engager sur une licence payante. L'essai vous permet d'explorer ses fonctionnalités premium, telles que la génération de fichiers PDF de haute qualité, les options de sécurité et la modification de documents PDF existants, vous offrant une expérience pratique des capacités de l'outil. Si votre projet nécessite des conversions fréquentes de HTML en PDF ou une édition complexe de PDF, l'essai gratuit d'IronPDF est un excellent moyen de voir s'il répond à vos besoins.
En évaluant les fonctionnalités spécifiques de chaque outil et la portée de votre projet, vous pouvez choisir la meilleure solution pour générer des fichiers PDF efficacement en C#.
10 produits API .NET pour vos documents de bureau