Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
The C# generate PDF functionality is critical for many modern applications, from creating reports to invoicing systems. In this article, we will explore six popular ways to generate PDF files using C#, highlighting both code-based libraries, such as IronPDF, and online API's and tools. Whether you need to generate PDF file dynamically in a web app or simply create PDF files from existing documents, these tools have you covered.
Broken image Add from Pixabay, select from your files or drag and drop an image here.
IronPDF is a premium .NET PDF library designed for developers who need high-quality HTML to PDF file conversion. IronPDF uses a Chromium-based rendering engine to ensure precise conversions, making it a perfect choice for web applications that want to convert HTML pages or web-based reports into PDF files in C#. The tool is known for its robust handling of existing PDF documents and provides features to edit, merge, or split PDFs.
IronPDF integrates easily into C# projects through NuGet Package Manager, and with just a few lines of code, you can start generating PDF documents. It’s a versatile tool for both dynamic HTML content and server-generated PDF file outputs.
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
Namespace Import: using IronPdf; imports the IronPDF library to access its classes and methods.
Renderer Instance: new ChromePdfRenderer(); creates an instance of the HtmlToPdf class, which provides methods for rendering HTML content into PDF format.
Render PDF: PdfDocument PDF = renderer.RenderHtmlAsPdf(html); converts the HTML string into a PDF document.
iTextSharp is a well-established .NET PDF library that provides extensive functionality for creating and editing PDF files. It is widely used in industries like finance and legal, where documents must be customized and secured. iTextSharp allows you to create PDF files from scratch, fill in forms, and modify PDF files, providing extensive control over the document's content. It is particularly useful for enterprise applications that need to generate PDF files with precise layouts and dynamic data, such as invoices or contracts.
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
GeneratePdfFromPage: Accepts a full HTML page and directly calls the generate method.
generate: This method handles the conversion of HTML to PDF.
It initializes a MemoryStream to hold the generated PDF in memory.
PDFSharp is a lightweight, open-source .NET PDF library ideal for basic PDF creation tasks. If your application requires only simple operations like adding text, images, or tables, PdfSharp is an easy-to-use option for generating PDF documents in C#. It lacks advanced features like HTML to PDF conversion but shines in its simplicity for generating small to medium-sized PDF files in 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 is a high-performance, comprehensive tool designed for enterprises that need to work with PDFs in a wide range of applications. It’s part of the broader Syncfusion suite, which offers libraries for a variety of formats and platforms. The PDF library stands out because of its extensive feature set that goes beyond simple document creation and allows for detailed manipulation, including form filling, digital signatures, and document security.
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 is a cloud-based service designed to convert HTML into PDF files. It integrates smoothly with C# applications via its API, allowing you to convert dynamically generated HTML web pages into professional-quality PDFs. PDFShift is particularly useful for web developers who want to generate PDFdocuments on demand from HTML content, such as invoices or reports. Since PDFShift operates entirely through its REST API, you can send just a few lines of HTML to the service and receive a downloadable PDF file in return. It’s a simple, scalable solution for web-based PDF file generation.
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 is another powerful API-based PDF generation service that converts HTML and CSS into high-quality PDFs. It is known for its excellent rendering of HTML documents, particularly in handling complex CSS styles, media queries, and web fonts. This makes DocRaptor a great choice for generating professional-looking documents like reports, invoices, and eBooks, directly from HTML templates.
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
If you don’t want to write code or need a quick solution for generating PDFs, several online tools allow you to create PDFs quickly and easily. Here are a few notable options:
Smallpdf is an online platform offering a variety of PDF-related tools, including the ability to create PDFs from a wide range of file formats. It’s designed for users who want a simple drag-and-drop interface without needing to write code. Smallpdf is widely used for quick file conversions, such as turning Word documents, Excel sheets, or images into PDFs. It also provides tools for merging, compressing, and splitting PDFs, making it a versatile tool for basic PDF tasks.
PDFescape is an easy-to-use web-based PDF editor that allows users to create, edit, and view PDFs without the need for installing any software. It’s a great tool for those who need to make quick edits to PDFs, such as filling out forms, adding text annotations, or inserting images. PDFescape also offers tools for creating new PDFs from scratch, making it a flexible choice for basic document creation.
PDF Candy is a suite of free online PDF tools that covers a wide range of PDF-related tasks, from file conversion to editing. It’s an excellent choice for users who need to perform quick PDF operations without registering for an account or installing software. PDF Candy supports converting various file types, such as Word documents, images, and text files, into PDFs. It also provides tools for merging, splitting, and compressing PDFs.
Choosing the right tool to generate PDF files in C# depends on your needs. If you need to generate PDF documents from HTML content, IronPDF and PDFShift are excellent choices. iTextSharp and Syncfusion offer extensive customization options and control over document structure for more complex projects. For simpler, open-source solutions, PDFsharp is a reliable choice for modifying PDF files or creating basic PDFs. Finally, for non-developers, Smallpdf, PDFescape, and PDF Candy provide easy, code-free options for working with PDF files.
For those interested in trying IronPDF, making it an excellent option for developers to test out its HTML-to-PDF conversion and PDF manipulation features before committing to a paid license. The trial allows you to explore its premium features, such as high-quality PDF file generation, security options, and modifying existing PDF documents, giving you a hands-on experience with the tool’s capabilities. If your project requires frequent HTML-to-PDF conversions or complex PDF editing, IronPDF's free trial is a great way to see if it fits your needs.
By evaluating the specific features of each tool and your project’s scope, you can choose the best solution for generating PDF files efficiently in C#..
9 .NET API products for your office documents