How to convert HTML to PDF in C# using wkhtmltopdf
Table of contents
For new C# HTML-to-PDF projects, evaluate browser automation such as PuppeteerSharp(opens in a new tab) or the hosted Nutrient DWS Processor API. wkhtmltopdf is an archived Qt WebKit-based converter; the legacy walkthrough below is for applications that already depend on it. Choose based on rendering requirements, deployment, and whether documents can be processed by a hosted service.
Choose an HTML-to-PDF method for C#
- Existing wkhtmltopdf integration — Keep a tested binary and templates while assessing a migration. The project was archived in January 2023(opens in a new tab). Its older rendering engine can differ from current browsers.
- Browser automation — Evaluate PuppeteerSharp(opens in a new tab) when you need browser-driven rendering and can manage browser installation, updates, and execution in your environment.
- Hosted conversion — Nutrient DWS Processor API accepts conversion requests over HTTP. Your C# application sends the input to Nutrient’s service; this is the hosted approach shown later in the article.
- Local SDK integration — For processing within your application, see the separate Nutrient .NET HTML-to-PDF guide. It has its own installation and licensing requirements and isn’t the hosted API example below.
Test fonts, images, page breaks, and JavaScript-dependent content with your actual templates before selecting a method. HTML conversion by itself doesn’t guarantee PDF/UA accessibility; see the C# PDF library evaluation guide for that distinction.
Development considerations
wkhtmltopdf is no longer maintained. Its own project guidance(opens in a new tab) warns against processing untrusted HTML. Use a maintained alternative for new integrations and assess the risks of retaining a legacy binary.
For the hosted Processor API, obtain a key from the Nutrient dashboard(opens in a new tab) and check current pricing. Don’t treat the free usage as a fixed number of conversions: Cost depends on the operation and plan.
Requirements
- The .NET SDK required by the example; the legacy walkthrough below targets .NET 8.
- An editor such as Visual Studio Code(opens in a new tab) (VS Code).
- The C# extension(opens in a new tab) for VS Code.
- Basic knowledge of C# and .NET console applications.
Installing wkhtmltopdf
To install wkhtmltopdf, follow the steps for your machine below.
On Windows
- Download the wkhtmltopdf binary from the official website(opens in a new tab).
- Once the download is complete, extract the files to a directory of your choice.
- Add the directory containing the wkhtmltopdf binary to your system’s
PATHenvironment variable. This enables you to run the wkhtmltopdf command from anywhere on your system. - Verify that wkhtmltopdf is installed correctly by running the following command in your terminal:
where wkhtmltopdfThe wkhtmltopdf executable is in the installation directory, which defaults to C:\Program Files\wkhtmltopdf\bin.
On macOS and Linux
For an existing installation, locate the executable with:
command -v wkhtmltopdfwkhtmltopdf --versionDon’t rely on the old Homebrew cask command as a current installation path. Check the archived download list(opens in a new tab) for your operating system and architecture, or migrate to a maintained converter. Linux package availability and behavior depend on the distribution and build. Verify the binary before using the walkthrough below.
Creating a C# project for HTML-to-PDF conversion
Create a .NET 8 console project. Then enter its directory:
dotnet new console --framework net8.0 --name HtmlToPdfLegacycd HtmlToPdfLegacySave a trusted, self-contained HTML document as input.html in this project directory. For example:
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Conversion check</title></head><body><h1>Invoice</h1><p>Test document for HTML-to-PDF conversion.</p></body></html>Method 1 — Run an existing wkhtmltopdf binary from C#
Replace Program.cs with the following. Set FileName to the absolute path of your installed executable if it isn’t on PATH. Input and output paths resolve from the directory where you run the application, not from the executable’s directory.
using System;using System.Diagnostics;using System.IO;using System.Threading.Tasks;
class Program{ static async Task<int> Main() { var inputHtml = Path.GetFullPath("input.html"); var outputPdf = Path.GetFullPath("output.pdf");
if (!File.Exists(inputHtml)) { Console.Error.WriteLine($"Input file not found: {inputHtml}"); return 1; }
var startInfo = new ProcessStartInfo { FileName = "wkhtmltopdf", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; startInfo.ArgumentList.Add(inputHtml); startInfo.ArgumentList.Add(outputPdf);
try { using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start wkhtmltopdf.");
// Drain both streams while the process runs to avoid full pipe buffers. var stdoutTask = process.StandardOutput.ReadToEndAsync(); var stderrTask = process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); var stdout = await stdoutTask; var stderr = await stderrTask;
if (process.ExitCode != 0) { Console.Error.WriteLine($"Conversion failed (exit {process.ExitCode})."); Console.Error.WriteLine(stderr); Console.Error.WriteLine(stdout); return 1; }
if (!File.Exists(outputPdf) || new FileInfo(outputPdf).Length == 0) { Console.Error.WriteLine("No PDF output was produced."); return 1; }
Console.WriteLine($"Created {outputPdf}"); return 0; } catch (Exception error) { Console.Error.WriteLine($"Conversion failed: {error.Message}"); return 1; } }}ArgumentList(opens in a new tab) passes the two paths as separate arguments, including paths containing spaces. The example reads both diagnostic streams asynchronously before waiting for exit. This avoids the redirected-output deadlock pattern(opens in a new tab) in which a process fills its output buffer while the parent waits.
Run the example from the project directory:
dotnet runInspect output.pdf to check the rendered content. A zero exit code isn’t a visual-quality or accessibility check. This small example has no execution timeout; add one with process termination before adapting it to a long-running service.
Method 2 — HTML to PDF in C# using Nutrient API
Nutrient DWS Processor API provides hosted HTML-to-PDF conversion. Supply the HTML and any required assets according to the API request format. Keep the API key on the server and out of source control. The request shown below uses the /build workflow.
Setting up Nutrient API
First, ensure you have an API key from Nutrient API(opens in a new tab). You’ll use this key to authenticate your requests.
Open VS Code and open a terminal in VS Code (Control-backtick).
Create a new directory for your project and navigate into it:
Terminal window mkdir nutrientApiDemocd nutrientApiDemoInitialize a new C# project:
Terminal window dotnet new console --framework net8.0Install the RestSharp package:
Terminal window dotnet add package RestSharpReplace the contents of
Program.cswith the provided code:using System;using System.IO;using System.Threading.Tasks;using RestSharp;class Program{static async Task<int> Main(){var apiKey = Environment.GetEnvironmentVariable("NUTRIENT_API_KEY");if (string.IsNullOrWhiteSpace(apiKey)){Console.Error.WriteLine("Set NUTRIENT_API_KEY in your environment.");return 1;}var inputHtml = Path.GetFullPath("index.html");if (!File.Exists(inputHtml)){Console.Error.WriteLine($"Input file not found: {inputHtml}");return 1;}using var client = new RestClient("https://api.nutrient.io/build");var request = new RestRequest().AddHeader("Authorization", $"Bearer {apiKey}").AddFile("index.html", inputHtml, "text/html").AddParameter("instructions", "{\"parts\":[{\"html\":\"index.html\"}]}");try{var response = await client.ExecutePostAsync(request);if (!response.IsSuccessful || response.RawBytes is not { Length: > 0 }){Console.Error.WriteLine($"Conversion failed: {response.StatusCode}");Console.Error.WriteLine(response.ErrorMessage ?? response.Content);return 1;}var outputPdf = Path.GetFullPath("result.pdf");await File.WriteAllBytesAsync(outputPdf, response.RawBytes);Console.WriteLine($"Created {outputPdf}");return 0;}catch (Exception error){Console.Error.WriteLine($"Conversion failed: {error.Message}");return 1;}}}Set
NUTRIENT_API_KEYin your local shell environment or server secret configuration before running the program. Save a self-containedindex.htmlin the project directory. Then run the command from that directory. Don’t commit the key.RestSharp sends the file and the
instructionsparameter as multipart form fields. The upload fieldindex.htmlmatches thehtmlvalue in the instructions. See RestSharp’s parameter documentation(opens in a new tab) for this behavior;ParameterType.RequestBodyisn’t the named form-field pattern used here.Run the project using the terminal:
Terminal window dotnet runOpen
result.pdfin the project directory and check its layout. This example uploads only one HTML file; include referenced assets using the API’s documented upload format when testing real templates.
wkhtmltopdf vs. Nutrient DWS Processor API
| Requirement | wkhtmltopdf | Nutrient DWS Processor API |
|---|---|---|
| Deployment | Local executable managed by your team | Hosted service called over HTTPS |
| Maintenance | Archived project | Check current API documentation and service terms |
| Input assets | Resolve paths and resource access in the local environment | Supply HTML and required assets in the supported request format |
| Cost | Open source; your team manages execution | Usage-based commercial service; see current pricing |
| Best starting point | Existing integrations with tested templates | Applications that can send documents to a hosted conversion service |
Next steps
For an existing wkhtmltopdf application, verify its binary, input handling, and output before planning a migration. For a new C# integration, compare browser automation, the hosted Processor API, and the .NET SDK conversion guide using the same templates.
FAQ
wkhtmltopdf is a legacy local executable. The Nutrient DWS Processor API example uses a hosted service. Choose based on maintenance requirements, rendering results, and where your documents may be processed; evaluate the separate .NET SDK when you need local integration.
The example here uploads an HTML file. To use an in-memory string, encode it and send it using the API’s supported HTML upload format; a raw HTML request body isn’t interchangeable with the multipart /build request shown here.
Its older Qt WebKit engine supports a subset of browser behavior. Test your CSS and JavaScript-dependent content; don’t assume output will match a current browser.
No. wkhtmltopdf was archived on 2 January 2023 and is now read-only. The library still functions, but it no longer receives security patches, bug fixes, or browser-engine updates. For new or mission-critical applications, we recommend a commercial alternative like the Nutrient API.
Check the executable path, input path, working directory, exit code, and diagnostic output. Capture standard error as well as standard output, and avoid waiting for exit while redirected output buffers may fill.
The example sends document content to a hosted service. Review your organization’s data-handling requirements and the service’s security and contractual terms before processing sensitive documents. A SOC 2 Type 2 audit alone doesn’t establish suitability for every regulated workflow.