pdf libraries

pdf libraries

C#

C#

How to Generate PDF from HTML Using PdfSharp in C#

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Oct 24, 2024

Oct 24, 2024

Introducing PdfSharp: A Lightweight .NET PDF Library

PdfSharp is an open-source PDF library for .NET, enabling developers to create, read, and modify PDF documents programmatically. It’s an excellent choice for generating PDF reports in your SaaS applications due to its simplicity and flexibility.

You can check out the full documentation here.

Comparison Between PdfSharp and Other C# PDF Libraries

When selecting a PDF library for C#, it’s important to understand the strengths and weaknesses of each option:

PdfSharp

  • Lightweight and easy to use.

  • Open-source with an MIT license.

  • Great for basic PDF creation and manipulation.

  • Limited support for advanced features like HTML to PDF conversion natively.

iTextSharp

  • Powerful and feature-rich.

  • Supports advanced PDF functionalities.

  • Dual-licensed; free under AGPL, which may require open-sourcing your application, or paid commercial license.

  • Steeper learning curve due to its extensive capabilities.

PuppeteerSharp

  • Headless Chrome .NET API.

  • Excellent for rendering complex HTML/CSS/JS to PDF.

  • Larger in size due to Chromium dependency.

  • Ideal for generating PDFs that require full browser rendering.

Playwright

  • Similar to PuppeteerSharp but supports multiple browsers.

  • Provides high-fidelity rendering of web pages to PDF.

  • Also larger in size with more dependencies.

  • Suitable for cross-browser PDF generation needs.

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

Setting Up PdfSharp in Your C# Project

Quick Start: Installing PdfSharp and Dependencies

Install PdfSharp via the NuGet Package Manager:

Alternatively, use the Package Manager Console:

Configuring Your .NET Environment for Seamless PDF Generation

Add the necessary namespaces to your project:

using PdfSharp.Pdf;
using PdfSharp.Drawing

Ensure your project targets a compatible .NET framework version, such as .NET Framework 4.6.1 or later.

Implementing HTML to PDF Conversion with PdfSharp

Creating a Complete Invoice HTML/CSS File for Example

Here’s a more comprehensive HTML template for an invoice:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 0; }
        .invoice-box { max-width: 800px; margin: auto; padding: 30px; border: 1px solid #eee; }
        .header { text-align: center; font-size: 36px; color: #333; }
        .details { margin-top: 20px; }
        .details th { text-align: left; padding: 5px; background: #f5f5f5; }
        .details td { padding: 5px; }
        .total { text-align: right; margin-top: 20px; font-size: 24px; }
        .notes { margin-top: 30px; font-size: 14px; color: #555; }
    </style>
</head>
<body>
    <div class="invoice-box">
        <div class="header">Invoice</div>
        <table class="details">
            <tr>
                <th>Date:</th>
                <td>{{InvoiceDate}}</td>
            </tr>
            <tr>
                <th>Invoice #:</th>
                <td>{{InvoiceNumber}}</td>
            </tr>
            <tr>
                <th>Client:</th>
                <td>{{ClientName}}</td>
            </tr>
        </table>
        <table class="details" style="width:100%; margin-top:20px;">
            <tr>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Total</th>
            </tr>
            {{#each Items}}
            <tr>
                <td>{{Description}}</td>
                <td>{{Quantity}}</td>
                <td>{{Price}}</td>
                <td>{{LineTotal}}</td>
            </tr>
            {{/each}}
        </table>
        <div class="total">
            Grand Total: {{GrandTotal}}
        </div>
        <div class="notes">
            Notes: {{Notes}}
        </div>
    </div>
</body>
</html>

HTML Template Engines

To inject dynamic data into the HTML template, use a template engine like Scriban.

Using Scriban to Populate the Template

Install Scriban via NuGet:

Here’s how to use Scriban to fill the variables:

using Scriban;
using System;
using System.Collections.Generic;
var htmlTemplate = /* Your HTML template string */;
var template = Template.Parse(htmlTemplate);
var model = new {
    InvoiceDate = DateTime.Now.ToString("MMMM dd, yyyy"),
    InvoiceNumber = "INV-1001",
    ClientName = "Acme Corporation",
    Items = new List<dynamic> {
        new { Description = "Consulting Services", Quantity = 10, Price = 150, LineTotal = 1500 },
        new { Description = "Software License", Quantity = 5, Price = 200, LineTotal = 1000 }
    },
    GrandTotal = 2500,
    Notes = "Thank you for your business."
};
var result = template.Render(model

Step-by-Step Guide: Converting HTML to PDF

Since PdfSharp doesn’t natively support HTML to PDF conversion, use it alongside HtmlRenderer.PdfSharp.

Installing HtmlRenderer.PdfSharp

Rendering HTML to PDF

using TheArtOfDev.HtmlRenderer.PdfSharp;
using PdfSharp.Pdf;
// Render the HTML to PDF
PdfDocument pdf = PdfGenerator.GeneratePdf(result, PdfSharp.PageSize.A4);
// Save the PDF to a file
pdf.Save("invoice.pdf"

Troubleshooting Common Issues

When working with PdfSharp and HTML rendering, you may encounter some common issues:

  • Styles Not Applying Correctly

    • Ensure all CSS styles are inline or within the <style> tags.

    • Some advanced CSS features may not be supported.

  • Images Not Displaying

    • Use absolute paths or embed images using Base64 encoding.

Example:

<img src="data:image/png;base64,..." alt="Logo" />
  • Unsupported HTML Elements

    • Not all HTML elements are supported by HtmlRenderer.PdfSharp.

    • Stick to basic HTML and CSS for maximum compatibility.

  • Font Rendering Issues

    • Embed fonts or use standard web-safe fonts.

    • Custom fonts may require additional configuration.

How to Use a PDF API to Automate PDF Creation at Scale

For SaaS platforms, automating PDF generation at scale might require offloading the heavy lifting to a PDF API. By integrating APIs like pdforge you can handle high-volume PDF generation, complex formatting, and post-processing, all from a single backend 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

This code sends a POST request to the pdforge API, receives the generated PDF, and saves it locally.

Conclusion

PdfSharp offers a straightforward way to generate PDFs in C# applications, especially when combined with HtmlRenderer for HTML to PDF conversion. It’s ideal for projects that require a lightweight and cost-effective solution. However, if you need advanced features or plan to generate PDFs at scale, you might consider other libraries like iTextSharp or cloud-based APIs like PdfForge.

Choose PdfSharp when:

  • You need a free and open-source solution.

  • Your PDF generation needs are straightforward.

  • You prefer a lightweight library.

Consider Other Libraries when:

  • You require advanced PDF features

  • Licensing restrictions are not an issue.

  • You need better support for complex HTML/CSS rendering.

Opt for Third-Party PDF APIs, like pdforge when:

  • You need to generate PDFs at scale.

  • You prefer offloading processing to a cloud service.

  • You require high-fidelity rendering of complex web pages.

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