C# Integration

Learn how to generate PDFs from your C# application using the built-in HttpClient and System.Text.Json.

Why use PixelToPdf with C#?

C# and .NET power enterprise applications worldwide, and PixelToPdf integrates seamlessly with ASP.NET Core, Blazor, and console applications. With async/await support and strong typing, you get reliable PDF generation with minimal code. Perfect for invoices, reports, contracts, and any document your business needs.

Prerequisites

  • .NET 6+ (or .NET Framework 4.7.2+ with System.Text.Json NuGet package)
  • A PixelToPdf API key from your dashboard (free tier available)

Basic Example

This example uses .NET's built-in HttpClient to convert a webpage to PDF. We use Environment.GetEnvironmentVariable() to securely read the API key.

Program.cs
using System.Text;
using System.Text.Json;

var client = new HttpClient();

var request = new HttpRequestMessage(HttpMethod.Post, "https://api.pixeltopdf.com/convert/pdf");
request.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("PIXELTOPDF_API_KEY"));

var payload = new { source = "https://example.com" };
request.Content = new StringContent(
    JsonSerializer.Serialize(payload),
    Encoding.UTF8,
    "application/json"
);

var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();

var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("output.pdf", pdfBytes);

Console.WriteLine("PDF saved to output.pdf");

How it works: The HttpClient sends an async HTTP request. We serialize the payload with System.Text.Json and read the response as a byte array. The EnsureSuccessStatusCode() throws an exception if the request fails.

Convert HTML String

For dynamic documents, pass your HTML directly as a string. C#'s verbatim string literal (@"") makes it easy to write multi-line HTML without escaping.

HtmlToPdf.cs
using System.Text;
using System.Text.Json;

var client = new HttpClient();

var html = @"
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; padding: 40px; }
    h1 { color: #333; }
  </style>
</head>
<body>
  <h1>Hello, PixelToPdf!</h1>
  <p>This PDF was generated from HTML.</p>
</body>
</html>";

var request = new HttpRequestMessage(HttpMethod.Post, "https://api.pixeltopdf.com/convert/pdf");
request.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("PIXELTOPDF_API_KEY"));

var payload = new
{
    source = html,
    format = "A4",
    margin = new { top = "20mm", bottom = "20mm", left = "20mm", right = "20mm" }
};

request.Content = new StringContent(
    JsonSerializer.Serialize(payload),
    Encoding.UTF8,
    "application/json"
);

var response = await client.SendAsync(request);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("output.pdf", pdfBytes);

Tip: You can use Razor templates or any .NET templating engine to generate your HTML dynamically. Anonymous types work great for the JSON payload, and the margin option accepts values in mm, cm, in, or px.

With ASP.NET Core

This ASP.NET Core controller creates an endpoint that generates PDFs on-demand. When users visit /api/invoice/123/pdf, they'll download the invoice as a PDF file.

InvoiceController.cs
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Text.Json;

[ApiController]
[Route("api/[controller]")]
public class InvoiceController : ControllerBase
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _config;

    public InvoiceController(IHttpClientFactory httpClientFactory, IConfiguration config)
    {
        _httpClient = httpClientFactory.CreateClient();
        _config = config;
    }

    [HttpGet("{id}/pdf")]
    public async Task<IActionResult> DownloadPdf(string id)
    {
        var request = new HttpRequestMessage(
            HttpMethod.Post,
            "https://api.pixeltopdf.com/convert/pdf"
        );
        request.Headers.Add("X-API-Key", _config["PixelToPdf:ApiKey"]);

        var payload = new { source = $"https://yourapp.com/invoice/{id}/html" };
        request.Content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json"
        );

        var response = await _httpClient.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            return StatusCode(500, "PDF generation failed");
        }

        var pdfBytes = await response.Content.ReadAsByteArrayAsync();

        return File(pdfBytes, "application/pdf", $"invoice-{id}.pdf");
    }
}

Best practice: Use IHttpClientFactory instead of creating HttpClient instances directly to avoid socket exhaustion. Store your API key in appsettings.json as "PixelToPdf:ApiKey" and access it via IConfiguration.

Error Handling

This reusable client class wraps the API call with proper error handling. The switch expression (C# 8+) provides clean, exhaustive handling of different HTTP status codes.

PixelToPdfClient.cs
using System.Text;
using System.Text.Json;

public class PixelToPdfException : Exception
{
    public PixelToPdfException(string message) : base(message) { }
}

public class PixelToPdfClient
{
    private readonly HttpClient _client;
    private readonly string _apiKey;

    public PixelToPdfClient(string apiKey)
    {
        _client = new HttpClient();
        _apiKey = apiKey;
    }

    public async Task<byte[]> GeneratePdfAsync(string source)
    {
        var request = new HttpRequestMessage(
            HttpMethod.Post,
            "https://api.pixeltopdf.com/convert/pdf"
        );
        request.Headers.Add("X-API-Key", _apiKey);

        var payload = new { source };
        request.Content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json"
        );

        var response = await _client.SendAsync(request);

        return response.StatusCode switch
        {
            System.Net.HttpStatusCode.OK =>
                await response.Content.ReadAsByteArrayAsync(),
            System.Net.HttpStatusCode.Unauthorized =>
                throw new PixelToPdfException("Invalid API key"),
            System.Net.HttpStatusCode.PaymentRequired =>
                throw new PixelToPdfException("No credits remaining"),
            System.Net.HttpStatusCode.TooManyRequests =>
                throw new PixelToPdfException("Rate limit exceeded"),
            _ =>
                throw new PixelToPdfException($"PDF generation failed: {response.StatusCode}")
        };
    }
}

// Usage
var client = new PixelToPdfClient(Environment.GetEnvironmentVariable("PIXELTOPDF_API_KEY")!);
var pdf = await client.GeneratePdfAsync("https://example.com");
await File.WriteAllBytesAsync("output.pdf", pdf);

Important: The API returns different status codes for different error types: 401 for authentication issues, 402 when you need more credits, and 429 when you've hit the rate limit. Handle each appropriately in production.

Next steps

You've mastered the basics! Learn about headers, footers, page breaks, and advanced styling in our API documentation.