In this guide you will learn how to convert HTML to PDF in C# and .NET using the HTML2PDF REST API. We will cover:
- Converting a URL to PDF with C#
- Converting raw HTML to PDF
- Setting page size, orientation and layout options
- Handling errors and status codes
Just like in other languages, the HTML2PDF API accepts both URLs and HTML
and returns the generated PDF as the HTTP response. You call
https://api.html2pdf.co.uk/ with your license key and parameters.
Prerequisites
- .NET 6 or later (the code also works on several earlier versions with minor changes)
- Reference to
System.Net.Http - An HTML2PDF license key
1. Convert a URL to PDF in C# / .NET
This example shows how to convert a public URL to a PDF file using HttpClient.
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Html2PdfExample
{
private static readonly string Endpoint = "https://api.html2pdf.co.uk/";
private static readonly string LicenseKey = "yourlicensekey";
public static async Task UrlToPdfAsync(string sourceUrl, string outputPath)
{
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(60)
};
var uriBuilder = new UriBuilder(Endpoint)
{
Query = $"license={Uri.EscapeDataString(LicenseKey)}&url={Uri.EscapeDataString(sourceUrl)}"
};
using var response = await httpClient.GetAsync(uriBuilder.Uri, HttpCompletionOption.ResponseHeadersRead);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTML2PDF API error: {(int)response.StatusCode} {response.ReasonPhrase}");
}
await using var responseStream = await response.Content.ReadAsStreamAsync();
await using var fileStream = File.Create(outputPath);
await responseStream.CopyToAsync(fileStream);
}
public static async Task Main()
{
await UrlToPdfAsync("https://example.com", "example.pdf");
Console.WriteLine("PDF created.");
}
}
This is often enough for generating PDF versions of invoices, reports or other pages in an ASP.NET or console application.
2. Convert raw HTML to PDF in C# / .NET
If the HTML is generated inside your application and is not available through a public URL, you can send the HTML directly to the API with a POST request.
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
public class Html2PdfHtmlExample
{
private static readonly string Endpoint = "https://api.html2pdf.co.uk/";
private static readonly string LicenseKey = "yourlicensekey";
public static async Task HtmlToPdfAsync(string html, string outputPath)
{
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(60)
};
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("license", LicenseKey),
new KeyValuePair<string, string>("html", html),
});
using var response = await httpClient.PostAsync(Endpoint, content);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTML2PDF API error: {(int)response.StatusCode} {response.ReasonPhrase}");
}
await using var responseStream = await response.Content.ReadAsStreamAsync();
await using var fileStream = File.Create(outputPath);
await responseStream.CopyToAsync(fileStream);
}
public static async Task Main()
{
var html = @"<html><body><h1>Hello from C#</h1><p>Converted with HTML2PDF.</p></body></html>";
await HtmlToPdfAsync(html, "csharp-html.pdf");
Console.WriteLine("PDF created from HTML.");
}
}
This method is ideal when you render a view or template to a string and do not want to expose it as a URL.
3. Setting conversion options
You can control the PDF output with additional query parameters. Common options include:
page_size(for exampleA4orLetter)orientation(portraitorlandscape)css_media_type(screenorprint)lazy_loadandwait_timefor pages that use lazy loading or heavy JavaScript
public static async Task UrlToPdfWithOptionsAsync(string sourceUrl, string outputPath)
{
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(60)
};
var query = $"license={Uri.EscapeDataString(LicenseKey)}" +
$"&url={Uri.EscapeDataString(sourceUrl)}" +
$"&page_size=A4" +
$"&orientation=landscape" +
$"&css_media_type=print" +
$"&lazy_load=true" +
$"&wait_time=3000";
var uriBuilder = new UriBuilder(Endpoint)
{
Query = query
};
using var response = await httpClient.GetAsync(uriBuilder.Uri, HttpCompletionOption.ResponseHeadersRead);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTML2PDF API error: {(int)response.StatusCode} {response.ReasonPhrase}");
}
await using var responseStream = await response.Content.ReadAsStreamAsync();
await using var fileStream = File.Create(outputPath);
await responseStream.CopyToAsync(fileStream);
}
For a full overview of all options, including headers, footers and watermarks, see the HTML2PDF API documentation.
4. Handling Errors
If the API cannot return a PDF, it responds with an HTTP status code instead. The most important ones are:
| Code | Description |
|---|---|
| 200 OK | Conversion succeeded and the response body contains the PDF |
| 400 Bad Request | No URL or HTML was provided |
| 401 Authorization required | Missing or invalid license key |
| 429 Too Many Requests | You exceeded the limits of your plan |
| 504 / 599 | Timeout or connectivity problems when fetching the URL |
In C# you can check response.StatusCode and decide whether to log the error,
show a message to the user or retry if the problem was temporary.
5. Next Steps
You now have the building blocks to integrate HTML to PDF conversion into your .NET applications. From here you can:
- Explore all parameters in the full API documentation
- Add a Click to PDF link on your site for one-click downloads
- Compare plans on the pricing page