HTML-to-PDF Generator for .NET C# WkHtmlToPdf wrapper


features convert HTML to PDF in C#

  • Create PDF from HTML with one line of C# code. Full support of complex HTML layouts, CSS, images/svg, custom fonts, javascript code.
  • Precise rendering: in 99% cases PDF result is identical to the web browser view: based on WkHtmlToPdf tool that uses QtWebKit engine.
  • Simplest way to generate PDF in .NET apps (ASP.NET Core MVC, .NET Core, NET6+, legacy ASP.NET):
    • create PDF from HTML string, file or URL
    • convert ASP.NET web page to PDF, MVC view to PDF
    • merge several HTML pages (files, URLs) into one resulting PDF
  • PDF options:
    • page orientation, custom page size, page margins, zoom
    • HTML template for page header/footer, page numbering, cover page
    • automatic table of contents generation by headings (H1/H2/H3)
  • Stable and time-proven solution for C# HTML to PDF conversion: all you need is one .NET assembly (wkhtmltopdf binaries for Windows are included).
  • LT-version for non-Windows deployments: NReco.PdfGenerator.LT.
  • PdfGenerator C# examples (NET6):
    • DemoMvc: online demo (generate PDF from HTML template or URL) + generate PDF from ASP.NET MVC views. Illustrates: page breaks, multi-page tables, cover page and table-of-contents, custom header/footer with page numbering
    • DataSetReport: generates PDF export of data table from DataSet using XSLT
    • EncryptPdf: how to generate secured (password protected) PDF
    • MergePdf: produce several PDFs and merge whem into one file with iTextSharp
    • WatermarkPdf: how to generate PDF and watermark it with background image or text (watermarked PDF example)
    • PdfFromFiles: generate one PDF from several HTML documents (files, URLs)
    • BatchMode: optimized generation of several PDF documents in the batch mode

download and pricing

quick purchase process

  • 1 Choose a package
  • 2 Pay online Online payment methods
  • 3 Download the package

NReco.PdfGenerator converts HTML page (with full CSS/images/js support) to PDF file with one line of C# code.

In 2024 wkhtmltopdf remains the easiest way to generate PDF invoices/orders/e-tickets, report exports etc. Don't spend your time and money on wkhtmltopdf integration into your .NET application: it's already done!

how to use

  1. Install NReco.PdfGenerator nuget package
  2. Convert HTML to PDF in your C# code:
    var htmlContent = String.Format("<body>Hello world: {0}</body>", 
    		DateTime.Now);
    var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
    var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
  3. Create PDF from HTML file or URL:
    htmlToPdf.GeneratePdfFromFile("http://www.nrecosite.com/", null, "export.pdf");
  4. That's all! See also online PdfGenerator API documentation.
Feel free to contact us in case of any questions.

convert HTML to PDF online

HTML template to convert:
OR convert web page to PDF (click to enter URL)
Note PDF generation may take some time (several seconds).

frequently asked questions

NReco.PdfGenerator can be used for FREE in .NET apps that have only one single-server production deployment.

A commercial license is required for:
  • Applications with multiple deployments, or one multi-server production deployment
  • SaaS apps

PdfGenerator renders web page like a web browser and can load external resources like images, CSS and js files (javascript code is executed just before PDF rendering).

If you found that your image/css/js file is not loaded:
  • when GeneratePdf is used: ensure that external resource is referenced with absolute (full) URL. Local file should have absolute path (without 'file://' prefix). GeneratePdf method cannot handle relative locations (use GeneratePdfFromFile instead).
  • ensure that referenced file is accessible and doesn't require authentication
  • if everything seems fine but file is still not loaded you may check detailed WkHtmlToPdf log:
    var htmlToPdf = new HtmlToPdfConverter();
    htmlToPdf.Quiet = false;
    htmlToPdf.LogReceived += (sender, e) => {
    	Console.WriteLine("WkHtmlToPdf Log: {0}", e.Data);
    };
PdfGenerator executes WkHtmlToPdf command line tool in a separate process using System.Diagnostics.Process API and your hosting environment/platform should allow that.

WkHtmlToPdf is based on QtWebKit 4.8 (rather old version from 2011) so it doesn't support modern CSS3 features (like flex/grid layout).

Component cannot be used (does not work) if wkhtmltopdf cannot be deployed (installed) and executed via System.Diagnostics.Process API: most shared ASP.NET hostings, UWP/Univeral Apps, mobile apps.
  • Azure Apps / Azure Functions (Windows) with a VM-based subscription plan (Basic, Standard, Premium) can use NReco.PdfGenerator with the following limitation: custom fonts cannot be loaded because of this specific hosting environment technical restrictions (it is possible to use only standard Windows fonts like Arial, Times New Roman etc).
    In the case of Azure Functions (Windows) + NReco.PdfGenerator nuget a default location for wkhtmltopdf binaries should be changed in this way:
    htmlToPdf.PdfToolPath = Path.Combine( Path.GetTempPath(), "wkhtmltopdf" );
    Shared Azure Apps plan is NOT supported.
  • Azure Apps / Azure Functions (Linux) is supported via NReco.PdfGenerator.LT nuget + containerized Azure Functions deployment. Instructions for docker + wkhtmltopdf deployment are listed below.
  • No restrictions when your .NET app that uses NReco.PdfGenerator is hosted on 'normal' Windows or Linux VM (Azure VM instance, AWS EC2 instance).
  • AWS Lambda is supported via NReco.PdfGenerator.LT nuget + this special wkhtmltopdf deployment.

Legacy .NET Framework 4.5+ apps are fully supported.

.NET Core/ NET6/NET8 apps
Starting from version 1.2.1 it is possible to reference NReco.PdfGenerator nuget in modern .NET apps and get leverages of simplified deployment (no need to deploy wkhtmltopdf separately). This will work only for Windows deployments.
For cross-platform apps (Linux, Mac-OS, Docker) another nuget NReco.PdfGenerator.LT should be used instead (API is 100% the same). Since this version doesn't include wkhtmltopdf binaries you need to deploy wkhtmltopdf for your target platform(s) with your .NET app separately.

LT build usage
The following C# code snippet illustrates how to initialize LT build:
var htmlToPdfConv = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdfConv.License.SetLicenseKey(
	"your_id", "your_license_key");

// for Linux/OS-X: "wkhtmltopdf"
htmlToPdfConv.WkHtmlToPdfExeName = "wkhtmltopdf.exe";

// specify where wkhtmltopdf binaries are installed/deployed
htmlToPdfConv.PdfToolPath = "<path_to_folder_with_wkhtmltopdf>";
htmlToPdfConv.GeneratePdfFromFile(
	"http://www.google.com", null, "google.pdf");
If you want to test LT nuget package you can contact support and ask for a demo key.
It is possible to specify custom header/footer in the following way:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PageHeaderHtml = "<div style='text-align:right;'>HEADER <span class='page'></span> of <span class='topage'></span> </div>";
If PDF is produced from several HTML inputs header/footer may be specified individually for each HTML:
htmlToPdf.GeneratePdfFromFiles(
  new [] {
    new WkHtmlInput("https://wkhtmltopdf.org/") {
      PageHeaderHtml = "HEADER 1"
    },
    new WkHtmlInput("https://www.google.com") {
      PageHeaderHtml = "HEADER 2"
    },
  },
  null,
  "multi_header.pdf"
);
Note that this GeneratePdfFromFiles overload can be used only with a license key.
It is possible to render table headers on each PDF page and get correct page breaks with long tables:
  • wrap header row(s) with THEAD.
  • specify CSS rule page-break-inside:avoid for TR, TH, TD.
Note: wkhtmltopdf still has several open issues related to rendering long tables (for example, if table has cell that take more than one page).
In some cases PDF generation fails with one of the following errors:
  • Exit with code 1 due to network error: ContentNotFoundError
  • Exit with code 1 due to network error: ProtocolUnknownError
  • Exit with code 1 due to network error: HostNotFoundError
This error means that input HTML has external js/css/image URL reference(s) that cannot be loaded by WkHtmlToPdf. In most cases PDF can be generated by specifying additional WkHtmlToPdf parameter:
var htmlToPdf = new HtmlToPdfConverter();
htmlToPdf.CustomWkHtmlArgs = " --load-media-error-handling ignore ";
There are 2 ways how ASP.NET web page can be exported to PDF:
  1. use GeneratePdfFromFile method and specify absolute URL to ASP.NET MVC Core page as an input. If this page requires authentication (cookie) it may be specified in this way:
    var authCookieName = "your_app_auth_coookie_name";
    htmlToPdf.CustomWkHtmlArgs = String.Format(" --cookie {0} {1} ", authCookieName, HttpContext.Request.Headers[authCookieName]);
  2. Render MVC Core Razor view to string, and then render it to PDF. This approach is illustrated in "DemoMvc" example ( ViewPdfResult.cs).
You can force wkhtmltopdf to use print media type by specifying the following option:
var pdfGen = new HtmlToPdfConverter();
pdfGen.CustomWkHtmlArgs ="  --print-media-type ";
Note that in some cases (esp. when page has complex javascript - for example, that renders dynamic SVG charts) this option may cause wkhtmltopdf crush. As alternative to "--print-media-type" you may use extra CSS file that applied only when PDF is generated.

This is known wkhtmltopdf (Windows) issue when letters are rendered too close to each other (condensed). Usually this effect appears with system-installed fonts (Arial, Times New Roman etc) and small font sizes.

There are 2 known workarounds:

  • use custom font (registered with @font-face)
  • set custom DPI value with wkhtmltopdf "dpi" option, for example -dpi 300 (values >=200 usually fix letter spacing).
NReco.PdfGenerator is a .NET wrapper for wkhtmltopdf and this means that wkhtmltopdf (a command line tool) should be deployed on your hosting environment. When your .NET app is hosted inside Docker container (Debian-based Linux) to deploy wkhtmltopdf the following commands should be added into your image's 'Dockerfile':
RUN apt-get update && apt-get install -y --no-install-recommends wget ca-certificates fontconfig libc6 libfreetype6 libjpeg62-turbo libpng16-16 libssl1.1 libstdc++6 libx11-6 libxcb1 libxext6 libxrender1 xfonts-75dpi xfonts-base zlib1g
RUN wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6.1-2/wkhtmltox_0.12.6.1-2.bullseye_amd64.deb
RUN dpkg -i wkhtmltox_0.12.6.1-2.bullseye_amd64.deb

Do NOT install wkhtmltopdf via apt-get install -y wkhtmltopdf because most likely you'll install legacy (old) version and possibly wrong build (without 'patched' QT).

If you want to use Windows fonts (Arial, Times New Roman, Courier New etc) add these commands into 'Dockerfile':
RUN sed -i'.bak' 's/$/ contrib/' /etc/apt/sources.list
RUN echo "ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true" | debconf-set-selections
RUN apt-get update -y && apt-get install -y --no-install-recommends ttf-mscorefonts-installer

what's new

2023 Jan 08 v.1.2.1 changes:
  • added netstandard2.0 build for NReco.PdfGenerator nuget (includes wkhtmltopdf): now it can be used in NET6/NET8/.NET Core apps (Windows deployments only) with free offering!
  • added more options to PageSize enum (A0-A9, B0-B9, Legal)
  • added static License.SetLicenseKey to set a license key globally (for all HtmlToPdfConverter instances)
2020 Jun 13 v.1.2.0 changes:
  • wkhtmltopdf upgraded to 0.12.6 (released on 2020-Jun-11)
  • framework target changed to net45 (net20 is not supported any more)
2017 Mar 30 v.1.1.15 changes:
  • added GeneratePdfFromFiles overload that accepts individual options (like header/footer) for each input. This function is available only for commercial users.
2017 Feb 18 v.1.1.14 changes:
  • WkHtmlToPdf tool upgraded to version 0.12.4 (released 2016-Nov-22)
  • all necessary VC++ Runtime 2015 dlls are included
  • for ASP.NET apps wkhtmltopdf binaries are extracted to App_Data\wkhtmltopdf by default
2016 Feb 03 v.1.1.12 changes:
  • WkHtmlToPdf tool upgraded to version 0.12.3.1 (released 2016-Jan-30).
  • fixed bug in batch mode (null reference exception for large HTML input)
  • added LT build: PdfGenerator without embedded wkhtmltopdf.exe (commercial package only)
2015 Dec 06 v.1.1.11 changes:
  • fixed batch mode issue (exception because of incorrect file path handling)
2015 Oct 01 v.1.1.10 changes:
  • fixed issue with "Exit with code 1 due to network error" workaround for overloads that accept output file path
  • added GeneratePdf(html,coverHtml,outputPdfFilePath) overload.
  • now VC++ runtime libs (required by wkhtmltopdf) are bundled for simplified deployment: no need to install VC++ 2013 redistributable package)
2015 Aug 29 v.1.1.9 changes:
  • added batch mode (BeginBatch/EndBatch): reuse the same wkhtmltopdf.exe process for processing several HTML templates (20%-30% faster). This feature requires commercial license key.
  • some code refactoring for better maintainability
  • added workaround for "Exit with code 1 due to network error" wkhtmltopdf issue: when "--load-error-handling" or "--load-media-error-handling" set to "ignore" (or "skip") wkhtmltopdf generates PDF output but process is exited with code = 1 and as result WkHtmlToPdfException is thrown. Now this case is handled correctly (exception is not thrown if PDF is generated).
  • added workaround for wkhtmltopdf issue: when PDF is generated to stdout wkhtmltopdf uses temp file anyway and doesn't remove it from system temp folder
  • now NReco.PdfGenerator.dll is a signed (strongly named) assembly
2015 Jul 02 v.1.1.7 changes:
  • added GeneratePdfFromFiles overload that accepts several HTML files for generating one resulting PDF
  • added TempFilesPath property that allows to set custom location for temp files (useful in cases if TEMP folder is not accessible for write by ASP.NET process).
2015 Mar 03 v.1.1.6 changes:
2015 Feb 06 v.1.1.4 + v.1.1.5 changes:
  • use of stdin/stdout (instead of temp files) for performing in-memory PDF generation
  • added ExecutionTimeout property (useful for some cases when PDF generation should be limited in time)
  • added LogReceived event for handling wkhtmltopdf console log (useful for debug purposes or reading javascript errors/console.log messages in C# code)
  • added Quiet property (enabled by default). Can be disabled for getting all debug/info messages from wkhtmltopdf console.
2014 Dec 17 v.1.1.3: Added CustomWkHtmlCoverArgs and CustomWkHtmlTocArgs properties.
2014 Nov 15 v.1.1.2: Fix issue with generating PDF from HTML with broken references (exception is thrown if at least one external resource has broken link) + added GeneratePdfFromFile overload that generates PDF directly to output file.
2014 Nov 02 v.1.1: WkHtmlToPdf tool upgraded to latest stable version 0.12.1 (released June 26, 2014). NOTE: it doesn't support Windows Server 2003 / Windows XP any more.
API remains compatible with previous PdfGeneration versions BUT PDF result might be different. Newest version of WkHtmlToPdf fixes all issues related to page breaks inside tables, correctly handles header/footer height, works much faster and renders HTML more accurate.

+ additionally in this release fixed a bug with temp files (zero-length temp files are not removed after PDF generation).
2014 Jul 07 v.1.0.3: fixed issue with non-ASCII chars in header/footer.
2014 Jun 26 v.1.0.2: fixed issue with freezing (typical case is generating >40 PDF pages).
2014 May 07 v.1.0.1: custom HTML header/footer support (with page numbering tokens)
2014 Feb 10 Added overloads for generating PDF from HTML file
2013 Dec 19 Fixed issue when with first call when PdfGenerator is used from concurrent threads
2013 Nov 27 Some fixes, added TOC properties
2013 Nov 13 Added MVC and WebForm examples
2013 Sep 08 Initial PdfGenerator release

more components

  • Image Generator

    .NET wrapper WkHtmlToImage utility that generate pretty-looking images by HTML layout.

  • PDF-to-Image Renderer

    .NET wrapper for poppler tools that converts PDF pages to images or text (ASP.NET PDF viewer, PDF thumbnails, extract PDF text/images).