pdf libraries

pdf libraries

C#

C#

How to convert HTML to PDF using iTextSharp (Updated 2025)

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Feb 3, 2025

Feb 3, 2025

Introduction: Why iTextSharp?

iTextSharp is a robust PDF library for .NET, making it an excellent tool for generating PDF reports in SaaS applications, whether for invoices, summaries, or detailed documents. In this article, we’ll explore how to convert HTML to PDF using iTextSharp. By leveraging C# and this library, you’ll be able to integrate PDF generation seamlessly into your projects.

It’s available under AGPL or commercial licenses, so be mindful of licensing terms when building proprietary or enterprise solutions.

You can check out the full documentation here.

Comparison Between iTextSharp and Other C# PDF Libraries

When selecting a PDF library, it’s crucial to consider factors like functionality, ease of use, and licensing. Here’s how iTextSharp compares to other popular options:

Download comparison between pdf libraries using nuget trends

iTextSharp: The most popular pdf library for C#. A feature-rich library supporting advanced PDF creation and manipulation. Ideal for complex tasks but requires attention to licensing for commercial use.

PdfSharp: An open-source library suitable for basic PDF tasks. While it excels in creating PDFs from scratch, it lacks native support for HTML to PDF conversion without additional extensions.

QuestPDF: A modern, open-source library offering a fluent API for building PDFs using C#. It excels at programmatic PDF generation but doesn’t natively support HTML to PDF conversion.

PuppeteerSharp and Playwright: Headless browser tools that render HTML to PDF by simulating a browser environment. They handle modern HTML/CSS well but can introduce unnecessary overhead for simple tasks.

iTextSharp strikes a balance between functionality and performance, making it a solid choice for converting HTML to PDF in a .NET environment.

We also have a full comparison between C# PDF generation libraries, that you can check out here.

Guide to generate pdf from html using C# iTextSharp
Guide to generate pdf from html using C# iTextSharp

Setting Up iTextSharp in Your C# Project

Before diving into code, you’ll need to set up iTextSharp in your project.

Installing iTextSharp via NuGet in a .NET Environment

Use the NuGet Package Manager to install iTextSharp:

Install-Package iTextSharp -Version 5

Or via the Package Manager Console:

PM> Install-Package iTextSharp -Version 5

Ensure that your project targets a compatible .NET framework version.

Preparing Your Project for HTML to PDF Conversion

Add the necessary namespaces in your C# files:

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml

Verify that all dependencies are correctly referenced to avoid runtime issues.

Implementing HTML to PDF Conversion with iTextSharp

Let’s walk through creating a complete invoice in HTML/CSS and converting it to PDF.

Start by designing your invoice template in HTML:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .invoice-box {
            max-width: 800px;
            margin: auto;
            padding: 30px;
            border: 1px solid #eee;
        }
        .invoice-header { text-align: center; margin-bottom: 50px; }
        .invoice-details { width: 100%; border-collapse: collapse; }
        .invoice-details th, .invoice-details td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        .invoice-details th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <div class="invoice-box">
        <div class="invoice-header">
            <h1>{{ CompanyName }}</h1>
            <p>{{ Address }}</p>
        </div>
        <table class="invoice-details">
            <tr>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
            </tr>
            {% for item in Items %}
            <tr>
                <td>{{ item.Description }}</td>
                <td>{{ item.Quantity }}</td>
                <td>${{ item.Price }}</td>
                <td>${{ item.Total }}</td>
            </tr>
            {% endfor %}
            <tr>
                <td colspan="3" style="text-align:right;">Subtotal</td>
                <td>${{ Subtotal }}</td>
            </tr>
            <tr>
                <td colspan="3" style="text-align:right;">Tax</td>
                <td>${{ Tax }}</td>
            </tr>
            <tr>
                <td colspan="3" style="text-align:right;">Total</td>
                <td>${{ Total }}</td>
            </tr>
        </table>
    </div>
</body>
</html>

Save this HTML content as invoice_template.html.

Using Template Engines for Dynamic HTML Generation

To generate dynamic invoices populated with data, integrate a template engine like Razor or Scriban. This allows you to inject variables and loop over data structures.

Example with Scriban:

using Scriban;
string templateText = File.ReadAllText("invoice_template.html");
var template = Template.Parse(templateText);
var model = new {
    CompanyName = "Your Company",
    Address = "1234 Street, City, Country",
    Items = new[] {
        new { Description = "Product A", Quantity = 2, Price = 50, Total = 100 },
        new { Description = "Product B", Quantity = 1, Price = 75, Total = 75 }
    },
    Subtotal = 175,
    Tax = 17.5,
    Total = 192.5
};
string htmlContent = template.Render(model

This approach enables you to create personalized invoices by passing different data models.

Writing C# Code to Convert HTML to PDF

Now, let’s write the C# code to convert the HTML content into a PDF document:

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
namespace PdfGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            string htmlContent = /* Your dynamic HTML content from the template engine */;
            using (FileStream stream = new FileStream("invoice.pdf", FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A4, 25, 25, 30, 30);
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                using (StringReader sr = new StringReader(htmlContent))
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
                }
                pdfDoc.Close();
                writer.Close();
            }
            Console.WriteLine("PDF generation completed successfully."

Troubleshooting & FAQ

  1. Why are my CSS styles missing?

Ensure CSS is either inline or in the <style> block within the HTML. iTextSharp’s XMLWorker can struggle with linked external styles unless you reference absolute URLs or embedded styles.

  1. How do I handle images?

Use absolute paths or convert images to base64 for reliable rendering.

  1. What about special characters or fonts?

Specify the correct encoding (UTF-8) and embed fonts if you need special glyphs.

  1. How can I improve performance for large documents?

Consider streaming the PDF output and reusing iTextSharp objects if possible, or upgrading to iText7 which can offer better performance in some cases.

Scaling PDF Generation with a Third-Party API

homepage of pdforge

For larger SaaS platforms requiring automated PDF generation at scale, integrating a PDF Generation API like pdforge can offload the heavy lifting. This approach is ideal for SaaS platforms with high volumes of PDF requests.

With pdforge, you can create beautiful reports with flexible layouts and complex components with an easy-to-use opinionated no-code builder. Let the AI do the heavy lifting by generating your templates, creating custom components or even filling all the variables for you.

You can handle high-volume PDF generation from a single backend call.

Here’s an example of how to generate pdf with pdforge via an API call:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace PdfApiIntegration
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer your-api-key");
            var requestBody = new
            {
                templateId = "your-template",
                data = new { html = "your-html" }
            };
            var content = new StringContent(
                Newtonsoft.Json.JsonConvert.SerializeObject(requestBody),
                Encoding.UTF8,
                "application/json"
            );
            var response = await client.PostAsync("https://api.pdforge.com/v1/pdf/sync", content);
            if (response.IsSuccessStatusCode)
            {
                var pdfBytes = await response.Content.ReadAsByteArrayAsync();
                File.WriteAllBytes("invoice.pdf", pdfBytes);
                Console.WriteLine("PDF generated using PDFForge API.");
            }
            else
            {
                Console.WriteLine("Error generating PDF: " + response.ReasonPhrase

You can create your account, experience our no-code builder and create your first layout template without any upfront payment clicking here.

Conclusion: Choosing the Right PDF Workflow

iTextSharp is a formidable .NET library for HTML-to-PDF conversion, offering strong customization and PDF manipulation features.

When to Use iTextSharp: If you need fine-grained PDF control (forms, annotations), or you prefer an AGPL-based solution.

When to Consider Alternatives:

  • PuppeteerSharp for pixel-perfect rendering of modern CSS/JavaScript.

  • QuestPDF for a fluent, code-based layout approach.

  • PdfSharp for lightweight projects without heavy HTML needs.

If you don't want to waste time maintaining pdfs layouts and their infrastructure or if you don't want to keep track of best practices to generate PDFs at scale, third-party PDF APIs like pdforge will save you hours of work and deliver a high quality pdf layout.

Updated for 2025 to reflect the latest iTextSharp features and best practices.

Generating pdfs at scale can be quite complicated!

Generating pdfs at scale can be quite complicated!

We take care of all of this, so you focus on what trully matters on your Product!

We take care of all of this, so you focus on what trully matters on your Product!

Try for free

7-day free trial

Table of contents

Title