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

To convert an HTML string directly to PDF in C#, pass it to DinkToPdf through ObjectSettings.HtmlContent, then call converter.Convert(doc). With no output path configured, the conversion returns PDF bytes you can save, return from an API, or store. The key deployment requirement is that the wkhtmltopdf native library matches your operating system and process architecture.

Convert an HTML string to PDF with DinkToPdf

DinkToPdf is a .NET wrapper for wkhtmltopdf. Its documented flow is to create an HtmlToPdfDocument, set document-level options, add an object containing the HTML, and call Convert. The following example follows the wrapper README’s API pattern; check the namespace and API version in the package installed in your project.

using DinkToPdf;
using DinkToPdf.Contracts;

string html = "<!doctype html><html><head><meta charset="utf-8"><title>Report</title></head>" +
              "<body><h1>Monthly report</h1><p>Generated from an HTML string.</p></body></html>";

var converter = new SynchronizedConverter(new PdfTools());
var doc = new HtmlToPdfDocument
{
    GlobalSettings =
    {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Portrait,
        PaperSize = PaperKind.A4
    },
    Objects =
    {
        new ObjectSettings
        {
            HtmlContent = html,
            WebSettings = { DefaultEncoding = "utf-8" }
        }
    }
};

byte[] pdf = converter.Convert(doc);
File.WriteAllBytes("report.pdf", pdf);

The important part for direct conversion is HtmlContent = html; it supplies the markup without first writing an HTML file. The byte array can be written to disk, returned as a download, or passed to another component. DinkToPdf also supports file output through its output settings when that better fits the application.

Return the PDF from an ASP.NET Core endpoint

Once the converter has produced a byte array, an ASP.NET Core endpoint can return it with a PDF content type and a download name:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
app.MapGet("/report.pdf", (IConverter converter) =>
{
    string html = "<html><body><h1>Report</h1></body></html>";
    var doc = new HtmlToPdfDocument
    {
        GlobalSettings = { PaperSize = PaperKind.A4 },
        Objects =
        {
            new ObjectSettings
            {
                HtmlContent = html,
                WebSettings = { DefaultEncoding = "utf-8" }
            }
        }
    };

    byte[] pdf = converter.Convert(doc);
    return Results.File(pdf, "application/pdf", "report.pdf");
});

This endpoint assumes that IConverter has been registered and that the matching native library is available to the deployed application. Do not create a new converter for every request in a multi-threaded service; follow the wrapper’s documented synchronization and lifetime guidance.

Install the wrapper and prepare the native library

Install the DinkToPdf NuGet package, then follow its README to obtain and copy the wkhtmltopdf native library into the project root. Select the binary for the target operating system and 32-bit or 64-bit process architecture. A successful build alone does not prove that the native library will be found or loaded in the deployed environment.

  1. Add DinkToPdf: install the package version your application will use, and confirm its API namespace and target-framework compatibility.
  2. Choose the native binary: match both the OS and architecture of the running process—not merely the development machine.
  3. Include it in deployment: make sure the file is copied or otherwise made available where the wrapper expects it at runtime.
  4. Test the published application: run a conversion in the same OS, architecture, and hosting model used in production.

The Haukcode.WkHtmlToPdfDotNet fork says its NuGet package includes native binaries, but that does not remove the need to validate its version and deployment behavior for your runtime. See its README for the fork’s instructions. The DinkToPdf README documents the original wrapper’s setup and API.

Set page size, orientation, encoding, and rendering behavior

Use GlobalSettings for PDF-level settings such as paper size, orientation, and margins. Use ObjectSettings and its web settings for the HTML object and rendering-related configuration. The wkhtmltopdf manual identifies A4 as its default paper size; set the size explicitly when output must follow a defined document standard.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Need Where to configure Practical note
Paper size and orientation GlobalSettings Choose the required paper kind and portrait or landscape orientation.
Margins Global PDF settings Set margins explicitly when content must fit a print layout or leave room for headers and footers.
Text encoding WebSettings.DefaultEncoding For UTF-8 HTML, specify utf-8 so non-ASCII characters are interpreted correctly.
JavaScript and delayed rendering wkhtmltopdf rendering options The manual documents JavaScript enable/disable and delay options. Dynamic content may require an appropriate wait; do not assume scripts have completed immediately.
Print styling and links wkhtmltopdf rendering options The manual documents print media type and external-link options. Check the exact behavior needed in the generated PDF.
Local resources Local-file access option Local-file access is disabled by default for reading other local files from a local input unless access is allowed. Avoid enabling broader access unless required.

These options are documented in the wkhtmltopdf usage manual. Exact property names exposed by a .NET wrapper can vary by package version, so map the setting to the wrapper API you have installed rather than pasting a property name from a different release.

Use a synchronized converter in a service

DinkToPdf recommends SynchronizedConverter for multi-threaded applications. The README describes conversion tasks as queued and executed on one thread, and recommends registering the converter as a singleton for dependency injection. This is wrapper-specific behavior, not a claim that all wkhtmltopdf integrations share the same concurrency model.

builder.Services.AddSingleton<IConverter>(
    new SynchronizedConverter(new PdfTools()));

Inject IConverter into the code that creates documents, as in the endpoint example. DinkToPdf’s README reports testing with console applications and Kestrel-hosted web applications and APIs, but says it was not tested with IIS. If IIS is your hosting environment, treat compatibility as unestablished by that README and test the exact deployment carefully.

Check compatibility, maintenance, and input safety

wkhtmltopdf is an open-source LGPLv3 command-line tool that renders HTML to PDF using Qt WebKit and can run headlessly without a display service, according to its project overview. Its official usage manual identifies version 0.12.6 with patched Qt. These facts describe the renderer; they do not guarantee that a particular .NET wrapper, native binary, OS, or hosting model is compatible with your application.

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

NuGet lists DinkToPdf 1.0.8 as last updated on April 18, 2017. That age makes it important to verify the wrapper, native binary, .NET runtime, OS, architecture, and host before adopting it for new production work; the date alone does not prove that every deployment will fail. The package listing is on NuGet.

For user-provided markup, security needs deliberate review. The Haukcode.WkHtmlToPdfDotNet repository explicitly warns against using wkhtmltopdf with untrusted HTML and advises sanitizing user-supplied HTML and JavaScript. Treat sanitization and process isolation as important design considerations, and do not enable local-file access casually: rendered HTML should not be given broader access to local resources than the feature requires.

Troubleshoot common conversion failures

  • Native library not found or failed to load: confirm the native file is included in the published output, and that its OS and 32-/64-bit architecture match the process. Test the deployed artifact, not only the IDE launch.
  • Conversion returns an error or the service stalls: inspect whether the HTML depends on remote resources or JavaScript that has not finished loading. The wkhtmltopdf manual documents JavaScript controls and delay options; configure them deliberately and investigate load failures rather than masking them.
  • Characters appear as boxes or are corrupted: include a suitable charset declaration in the HTML and set DefaultEncoding to UTF-8 when the input is UTF-8.
  • Content is clipped or split unexpectedly: verify paper size, orientation, margins, and print styles. A screen-oriented layout may not fit the chosen page dimensions.
  • Images or styles are missing: check that referenced assets are reachable from the rendering process. If using local paths, understand the local-file access default and permit only the necessary access.
  • Unexpected behavior under IIS: DinkToPdf does not document IIS testing. Validate the native library loading, permissions, process architecture, and conversion behavior in the actual IIS deployment.
  • Concurrent requests behave unpredictably: use the synchronized converter and singleton registration recommended by DinkToPdf for multi-threaded service use; confirm request handling and resource limits in your own host.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your actual goal is to capture a live web page as a PDF or image rather than render an HTML string inside your C# process, ScreenshotNeo provides a website screenshot API and MCP server. A single request can return a screenshot or PDF. For example, this cURL request asks for a PDF of a URL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -d format=pdf -o page.pdf

See the ScreenshotNeo API documentation for the supported request parameters. It accepts cookie or consent banners before capture and removes 60+ known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with response headers indicating the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

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

Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month with no card.

Frequently Asked Questions

Does wkhtmltopdf convert a C# string without creating an HTML file?

Yes. With DinkToPdf, assign the string to ObjectSettings.HtmlContent and convert the document.

Does DinkToPdf return a PDF file or bytes?

With no output path set, its documented conversion call returns a byte[]; configure output settings when you want it to write to disk.

Can I use this approach with IIS?

DinkToPdf says its README did not test IIS, so verify the exact application and deployment rather than assuming support.

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

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.