pdf libraries

pdf libraries

C#

C#

Simplify PDF generation from HTML using QuestPDF

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Oct 27, 2024

Oct 27, 2024

Introduction to PDF Generation with QuestPDF

QuestPDF is an open-source .NET library designed to streamline the creation of PDF documents using C#. It offers a fluent API that simplifies the process of defining complex layouts and styles, making it an excellent choice for developers looking to generate PDF reports in their SaaS applications.

You can check out their full documentation here.

Comparison Between QuestPDF and Other C# PDF Libraries

When it comes to generating PDFs in C#, several libraries are available:

Download comparison between pdf libraries using nuget trends

iTextSharp: A mature library with extensive features but can be overkill for simple tasks and comes with licensing considerations.

PdfSharp: User-friendly and straightforward but lacks some advanced functionalities.

PuppeteerSharp and Playwright: Headless browser automation tools that can render HTML to PDF but may introduce unnecessary overhead.


QuestPDF stands out by providing a balance between functionality and simplicity, making it a compelling choice for .NET developers seeking efficient HTML to PDF conversion.

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

Setting Up QuestPDF in a .NET Environment

Installing and Configuring QuestPDF in a C# Project

To get started with QuestPDF, install it via the NuGet Package Manager:

Or using the .NET CLI:

Understanding the QuestPDF API for HTML to PDF Conversion

QuestPDF allows you to define document structures using C# code. While it doesn’t natively convert HTML to PDF, you can render HTML content by integrating it with HTML parsing libraries.

Integrating QuestPDF with Existing PDF Libraries for Enhanced Functionality

To enhance functionality, you can combine QuestPDF with libraries like AngleSharp for HTML parsing or PdfSharp for additional PDF manipulation features.

Step-by-Step Guide: Converting HTML to PDF Using QuestPDF

Building HTML Templates for PDF Reports

Start by creating an HTML template for your PDF report. Here’s an example of a simple invoice:

<!-- invoice.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%; margin-bottom: 20px; }
        .invoice-details th, .invoice-details td { padding: 15px; text-align: left; }
        .total { text-align: right; font-weight: bold; }
    </style>
</head>
<body>
    <div class="invoice-box">
        <div class="invoice-header">
            <h1>Invoice</h1>
            <p>Invoice #: @Model.InvoiceNumber</p>
            <p>Date: @Model.Date</p>
        </div>
        <table class="invoice-details">
            <tr>
                <th>Bill To:</th>
                <td>@Model.CustomerName</td>
            </tr>
            <tr>
                <th>Amount Due:</th>
                <td>$@Model.AmountDue</td>
            </tr>
        </table>
        <p class="total">Total: $@Model.AmountDue</p>
    </div>
</body>
</html>

HTML Template Engines

Utilize a template engine like Razor to inject dynamic data into your HTML:

string template = File.ReadAllText("invoice.html");
var model = new
{
    InvoiceNumber = 123,
    Date = DateTime.Now.ToShortDateString(),
    CustomerName = "John Doe",
    AmountDue = 150.00
};
string htmlContent = RazorEngine.Razor.RunCompile(template, "templateKey", null, model

Creating Dynamic and Interactive PDFs with QuestPDF

Use QuestPDF to render the HTML content into a PDF document:

using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using AngleSharp.Html.Parser;
public class InvoiceDocument : IDocument
{
    private readonly string _htmlContent;
    public InvoiceDocument(string htmlContent)
    {
        _htmlContent = htmlContent;
    }
    public DocumentMetadata GetMetadata() => DocumentMetadata.Default;
    public void Compose(IDocumentContainer container)
    {
        container.Page(page =>
        {
            page.Size(PageSizes.A4);
            page.Margin(2, Unit.Centimetre);
            page.Content().Element(BuildContent);
        });
    }
    void BuildContent(IContainer container)
    {
        var parser = new HtmlParser();
        var document = parser.ParseDocument(_htmlContent);
        container.Element().Row(row =>
        {
            row.RelativeItem().Column(column =>
            {
                // Parse and add HTML elements to the PDF
                foreach (var element in document.Body.Children)
                {
                    column.Item().Text(element.TextContent

Customizing the Output: Layout, Fonts, and Styles

Customize fonts and styles to match your branding:

page.DefaultTextStyle(x => x.FontSize(12).FontFamily("Helvetica"

Include images and custom layouts:

column.Item().Image("logo.png", ImageScaling.FitWidth

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.

Implementation Example in C#:

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

QuestPDF provides a robust solution for generating PDFs from HTML in .NET applications, especially when you require fine-grained control over the document structure and styling. It’s ideal for developers who prefer a code-centric approach using C#.

However, if you need to render complex HTML or require features beyond QuestPDF’s capabilities, alternatives like Playwright or third-party PDF APIs such as pdforge might be more suitable. Selecting the right tool depends on your project’s specific needs, performance requirements, and scalability considerations.

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