Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use WkHtmlToXSharp as a managed C# wrapper around wkhtmltopdf: install the WkHtmlToXSharp NuGet package, add the native bundle for your operating system and process architecture, configure global and object settings, then call Convert(). The native library is a separate deployment concern, and the wrapper API is version-sensitive, so verify property names against the exact package you install.

What WkHtmlToXSharp actually provides

WkHtmlToXSharp is a P/Invoke wrapper for the wkhtmltopdf HTML-to-PDF engine. Your C# code configures a converter; the native libwkhtmltox binary performs the rendering. The managed package and native binaries are separate NuGet packages.

The package registry lists version 1.2.39 (metadata updated July 16, 2026) and .NET Framework compatibility including net40-client. Because package metadata and APIs can change, pin the version in your project and record the native bundle version used in deployment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install the managed wrapper and native bundle

Add the managed package

From your project directory:

dotnet add package WkHtmlToXSharp --version 1.2.39

Or add an explicit reference to the project file:

<PackageReference Include="WkHtmlToXSharp" Version="1.2.39" />

Select the native package

Install the package matching both the operating system and the process architecture that will execute your application:

  • WkHtmlToXSharp.Win32 for a 32-bit Windows process.
  • WkHtmlToXSharp.Win64 for a 64-bit Windows process.
  • WkHtmlToXSharp.Linux32 for a 32-bit Linux process.
  • WkHtmlToXSharp.Linux64 for a 64-bit Linux process.

A 64-bit operating system does not by itself make a 32-bit process compatible. Check the process architecture produced by your build and container, and keep managed and native package versions aligned. If the native library cannot be loaded, fix that deployment mismatch before debugging HTML or CSS.

Deployment checklist

  • Pin the wrapper and native bundle versions.
  • Publish for the same architecture as the selected native package.
  • Include the native binary in the published application or container image.
  • Install fonts and any local assets required by your HTML.
  • Exercise a conversion in the target environment, not only on a developer workstation.

The basic conversion pipeline

A conversion has five parts: a converter, global PDF settings, one or more object settings, an HTML page or file, and the conversion call. This file-based example follows the commonly used WkHtmlToXSharp pattern:

using WkHtmlToXSharp;

string htmlFullPath = Path.GetFullPath("invoice.html");

IHtmlToPdfConverter converter = new MultiplexingConverter();

converter.GlobalSettings.Margin.Top = "0cm";
converter.GlobalSettings.Margin.Bottom = "0cm";
converter.GlobalSettings.Margin.Left = "0cm";
converter.GlobalSettings.Margin.Right = "0cm";
converter.GlobalSettings.Orientation = PdfOrientation.Portrait;
converter.GlobalSettings.Size.PageSize = PdfPageSize.A4;

converter.ObjectSettings.Page = htmlFullPath;

PdfDocument pdf = converter.Convert();
File.WriteAllBytes("invoice.pdf", pdf.ToBytes());

The exact output-writing member can differ by wrapper revision. If your installed assembly exposes a stream, byte array, or file-writing method instead of ToBytes(), use that member as shown by IntelliSense. The same caution applies to the converter and settings types: confirm names in the package you actually installed.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use an absolute local path

Resolve the HTML path before assigning it. Relative paths depend on the process working directory, which commonly changes under a service, test runner, Windows Task Scheduler, or container. Local CSS, images, and fonts should likewise use paths that the native renderer can access.

HTML strings and URLs

WkHtmlToXSharp versions expose different members for in-memory HTML. Some wrappers call it an HTML-content or HTML-text property; do not assume a member name from another library. Inspect the installed assembly and assign the string through the member provided by that version. For a remote page, assign its URL through the corresponding object setting and ensure the target environment can resolve DNS, establish TLS, and reach the site.

Configure page layout and PDF output

Paper size, orientation and margins

Use the global settings for document-wide layout. Common paper sizes include A4 and Letter. Choose portrait for conventional documents and landscape for wide tables. Margins are strings such as "10mm" or "0.5in"; set all four sides explicitly when predictable geometry matters.

Backgrounds, images and JavaScript

The underlying wkhtmltopdf web settings control whether backgrounds and images are printed, whether JavaScript executes, and how external resources load. Enable only what the page needs. A page that relies on client-side rendering can produce an empty or incomplete PDF when JavaScript is disabled or when conversion finishes before the script updates the DOM.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
// Property names vary by WkHtmlToXSharp version.
// Confirm the exact WebSettings members in IntelliSense.
converter.ObjectSettings.WebSettings.Background = true;
converter.ObjectSettings.WebSettings.LoadImages = true;
converter.ObjectSettings.WebSettings.EnableJavascript = true;

Older WebKit rendering does not imply complete support for modern browser CSS. Test the actual HTML with the wkhtmltopdf build shipped in your application, particularly when using newer grid, flexbox, font, or script features.

Headers, footers and metadata

Global options can define a document title and PDF output behavior. Object or global header/footer settings can add text, spacing, page numbers, and dates. Configure these through the API surface present in your installed package; names and nesting differ among wrapper releases.

Outlines and compression

wkhtmltopdf supports PDF outlines (bookmarks) and output controls such as grayscale and quality/compression options. Outline depth is useful for reports with heading structure, while grayscale can reduce file size when color is unnecessary. Measure the resulting file and readability for your document rather than assuming a setting is always beneficial.

A production-oriented example

This example validates the input, creates a dated output directory, and keeps conversion failures visible to the caller:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using WkHtmlToXSharp;

static string RenderPdf(string htmlPath, string outputPath)
{
    if (!File.Exists(htmlPath))
        throw new FileNotFoundException("HTML input was not found.", htmlPath);

    Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPath))!);

    IHtmlToPdfConverter converter = new MultiplexingConverter();
    converter.GlobalSettings.Margin.Top = "12mm";
    converter.GlobalSettings.Margin.Bottom = "12mm";
    converter.GlobalSettings.Margin.Left = "12mm";
    converter.GlobalSettings.Margin.Right = "12mm";
    converter.GlobalSettings.Orientation = PdfOrientation.Portrait;
    converter.GlobalSettings.Size.PageSize = PdfPageSize.A4;
    converter.ObjectSettings.Page = Path.GetFullPath(htmlPath);

    PdfDocument document = converter.Convert();
    File.WriteAllBytes(outputPath, document.ToBytes());
    return outputPath;
}

string result = RenderPdf("templates/report.html", "out/report.pdf");
Console.WriteLine($"Created {result}");

Replace ToBytes() if your installed version exposes a different serialization method. Keep one converter per conversion request unless the package documentation for your version explicitly guarantees safe concurrent reuse.

Choosing settings for common requirements

Requirement Settings to review Typical risk
Print-ready report A4 or Letter, portrait, explicit margins, backgrounds, images Unexpected page breaks or missing fonts
Wide data table Landscape, smaller margins, width-aware CSS Content shrinks or is clipped
Dashboard rendered by JavaScript JavaScript enabled, images enabled, adequate load delay PDF captures before data appears
Public web page URL input, external-resource access, title and outline settings Network, TLS, robots, or authentication failures
Small monochrome archive Grayscale and compression/quality options Loss of color cues or legibility

Troubleshoot failures systematically

“Unable to load library” or entry-point errors

The native package may target a different OS or architecture, the binary may be missing from the publish output, or managed and native versions may be mismatched. Confirm runtime architecture, inspect the published files, and align package versions before changing HTML.

Blank PDF or missing sections

Check that the HTML path is absolute and readable by the application account. For dynamic pages, enable JavaScript and images, then provide the version-specific delay or wait mechanism. Verify that external CSS, fonts, and images are reachable from the conversion host.

Modern CSS looks wrong

wkhtmltopdf uses a WebKit-based renderer and may not implement newer CSS behavior. Simplify the layout, provide print-specific CSS, or test a wkhtmltopdf-compatible alternative. Do not infer browser parity from a successful Chrome preview.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Images or fonts disappear

Use accessible absolute paths or URLs, check file permissions, and ensure fonts are installed in the target environment. Relative asset paths that work from an IDE often fail in a service or container.

Pages are clipped or unexpectedly scaled

Set paper size, orientation, and all margins explicitly. Review fixed widths, overflow rules, and intelligent-shrinking behavior. A wide element may be scaled down, wrapped, or clipped depending on the renderer and CSS.

Conversion hangs or times out

Look for unreachable network resources, scripts that never settle, or a page waiting for user interaction. Add an application-level timeout and cancellation strategy around the conversion process, and log the input URL/path plus the selected native build.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reliability, security and cost considerations

Rendering is performed by native code, so isolate conversion workers when processing untrusted HTML. Restrict outbound network access where possible, avoid passing secrets in URLs, and treat local-file access as a deployment security decision. Cache or reuse generated PDFs only when the source and settings are deterministic.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The NuGet page records 267.8K total downloads at the 2026 crawl; that registry count changes over time and is not a performance or support guarantee. There are no independent rendering benchmarks established here. Test representative documents, including long tables, remote assets, non-Latin text, and failure cases, in every target OS and architecture.

Or skip the browser setup

If your requirement is simply a clean screenshot or PDF of a web page rather than a local wkhtmltopdf pipeline, ScreenshotNeo provides a single HTTP endpoint. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status.

For a screenshot, call the API directly (see the ScreenshotNeo documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers PDF capture, full-page and element capture, device presets, custom viewports, JavaScript and CSS, waits, headers, cookies, geolocation, request blocking, caching, signed links, asynchronous webhooks, bulk capture and an MCP server with take_screenshot, get_page_info and capture_pdf for AI agents. One thousand screenshots per month are free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Is WkHtmlToXSharp itself the PDF engine?

No. It is the managed P/Invoke wrapper; wkhtmltopdf and its native library perform rendering.

Can I install only WkHtmlToXSharp?

For a working deployment, install the native bundle matching the runtime OS and architecture as well.

Should I target .NET Framework or modern .NET?

The package metadata lists .NET Framework targets including net40-client. Check the exact compatibility and native-loading behavior of your chosen package before selecting a target.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.