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


features convert HTML-to-PDF in C#

  • Create PDF from HTML page with one line of C# code. Full support of complex layout, 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 WebKit browser engine.
  • Simplest way to generate PDF from .NET applications (ASP.NET, ASP.NET MVC, WebForms, .NET Core, VB.NET):
    • create PDF from HTML string, file or URL
    • convert ASPX 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
    • HTML template for page header/footer, page numbering, cover page
    • automatic table of contents generation by headings (H1/H2/H3)
  • Simple and easy to use HTML-to-PDF .NET converter: all you need is one assembly. NReco.PdfGenerator.LT (without embedded WkHtmlToPdf binaries) may be used with custom non-windows wkhtmltopdf builds in Mono/.NET Core projects.
  • PdfGenerator C# examples package:
    • DataSetReport: generates PDF with data table from DataSet using XSLT
    • DemoMvc: 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
    • DemoWebForms: generate PDF from textarea (online demo)
    • EncryptPdf: how to generate secured (password protected) PDF
    • PdfFromFiles: how to generate one PDF from several HTML documents (files, URLs) with common header
    • WatermarkPdf: how to generate PDF and watermark it with background image or text (watermarked PDF example)
    • BatchMode: optimized generation of several PDF documents in the batch mode
    • WordToPdf: convert word to PDF (OpenXmlPowerTools is used for converting word docx file to HTML)
  • Looking for HTML to Image converter? Try NReco.ImageGenerator

download and pricing

quick purchase process

  • 1 Choose a package
  • 2 Pay online 2Checkout.com is a worldwide leader in online payment services
  • 3 Download the package
PdfGenerator converts HTML page (with full CSS/images/js support) to PDF file with one line of C# code. Don't spend your time and money on WkHtmlToPDF integration into your .NET application: it's already done!

how to use

  1. Download free package and add reference to the NReco.PdfGenerator.dll assembly OR install NReco.PdfGenerator nuget package
  2. Convert HTML to PDF with one line of 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 (WebForms, MVC page):
    htmlToPdf.GeneratePdfFromFile("http://www.nrecosite.com/", null, "export.pdf");
  4. That's all! See also online PdfGenerator API documentation.
Have a question? Feel free to ask.

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

PdfGenerator can be used for FREE in single-deployment projects (websites, intranet/extranet) or applications for company's internal business purposes (redistributed only internally inside the company).

Commercial license (included into enterprise pack) is required for:
  • Applications for external redistribution (ISV)
  • SaaS deployments

Also you may purchase standard commercial package if you need:
  • get license key for LT build or unblock batch mode feature (BeginBatch/EndBatch methods)
  • email support/assistance (note that support is NOT available for free users)
  • advanced usage examples

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 (x86 windows build) in the separate process with System.Diagnostics.Process and your project environment/platform should allow that.
Component cannot be used (does not work) in the following cases:
  • partial-trust environments where starting new processes is prohibited (shared ASP.NET hostings)
  • special Windows Server configurations with restricted access to GDI API. Azure Apps (former WebSites) are NOT supported!
  • .NET platforms where System.Diagnostics.Process API is not available (UWP/Univeral Apps)
PdfGenerator works fine with usual Azure VM instances (Web Role, Worker Role) and Azure Service Fabric.
Both .NET 2.0 and 4.0 runtimes are supported.

Linux + MONO, legacy windows versions (XP/2003 Server)
NReco.PdfGenerator assembly embeds windows build of wkhtmltopdf.exe (MSVC 2013) and it can work only under windows (Vista/2008 Server or later).
It is possible to overcome this limitation with special "light" PdfGenerator build (NReco.PdfGenerator.LT.dll). LT assembly doesn't include wkhtmltopdf.exe and can be used with non-windows wkhtmltopdf builds (OS X, Linux or MinGW build for legacy versions of windows).

.NET Core
NReco.PdfGenerator.LT nuget package includes build for .NET Standards 1.5 that can be used from .NET Core apps.
Note that you should deploy wkhtmltopdf binaries for your target platform(s) (Windows, Linux or OS X) with your .NET Core app.

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";
// path where wkhtmltopdf binaries are installed/deployed
htmlToPdfConv.PdfToolPath = "<path_to_wkhtmltopdf_folder>";
htmlToPdfConv.GeneratePdfFromFile(
	"http://www.google.com", null, "google.pdf");
Yes it is possible to specify custom header/footer with HTML template. It supports special tokens for current page number and total number of pages.
Starting from PdfGenerator v.1.1. (based on wkhtmltopdf 0.12.x) it is possible to render table headers on each page and get correct page breaks with long tables.
Note: wkhtmltopdf still has several open issues related to rendering long tables (for example, if table cells contain a lot of content).
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 ";
PdfGenerator can be used for converting Word documents (docx, Word 2007+) to PDF in the following way:
  • convert docx (OpenXML) to HTML using OpenXmlPowerTools library (open source). It correctly handles embedded images, styles, tables etc.
  • convert intermediate HTML file to PDF with PdfGenerator
This approach is illustrated by Word-To-Pdf C# example (included into commercial package).
There are 2 ways how ASPX page can be exported to PDF:
  1. use GeneratePdfFromFile method and specify absolute URL to ASPX page as input file path (simplest solution if ASPX page is doesn't require authentication).
  2. Override System.Web.UI.Page.Render method in the following way:
    protected override void Render(HtmlTextWriter writer) {
     if (Request["export"]=="pdf") {
      var strWr = new StringWriter();
      var htmlWr = new HtmlTextWriter(); 		
      base.Render(htmlWr);
      var htmlToPdf = new HtmlToPdfConverter();
      Response.ContentType = "application/pdf";
      htmlToPdf.GeneratePdf(strWr.ToString(), null, Response.OutputStream);
      Response.End();
     }
    }
    As result you can download PDF version of the ASPX page by adding "?export=pdf" query parameter.
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.

what's new

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 renders PDF pages to images (web preview, thumbnail etc).