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)
- Stable and time-proven solution for C# HTML to PDF conversion: all you need is one .NET assembly (wkhtmltopdf binaries are embedded into DLL).
- Has .NET Core compatible version: NReco.PdfGenerator.LT.
-
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
- MergePdf: produce several PDFs and merge whem into one file with iTextSharp
- PdfFromFiles: generate one PDF from several HTML documents (files, URLs)
- 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
download and pricing
PDF Generator FREE Binary pack
NO examples, NO support, NO batch mode, only for .NET Framework / windows environment. |
Download for Free |
PDF Generator examples & support binary pack
Includes: usage examples with source code (C#), license key for advanced functions and NReco.PdfGenerator.LT version, 1 year of email support and examples package updates |
$75 - Order Now |
PDF Generator enterprise source code pack
Includes: full component source code (C#) with examples, license key for advanced functions and NReco.PdfGenerator.LT version, extended license for DLL redistribution and SaaS usage, 1 year of email support and source code/examples updates |
$199 - Order Now |
quick purchase process
- 1 Choose a package
-
2 Pay online
- 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
- Download free package and add reference to the NReco.PdfGenerator.dll assembly OR install
NReco.PdfGenerator nuget package
- Convert HTML to PDF with C# code:
var htmlContent = String.Format("<body>Hello world: {0}</body>", DateTime.Now); var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter(); var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
-
Create PDF from HTML file or URL (WebForms, MVC page):
htmlToPdf.GeneratePdfFromFile("http://www.nrecosite.com/", null, "export.pdf");
- That's all! See also online PdfGenerator API documentation.
convert HTML to PDF online
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 source code pack) is required for:
Commercial license (included into enterprise source code pack) is required for:
- Applications for external redistribution (ISV), multiple deployments
- SaaS deployments
Also you may purchase examples&support commercial package if you need:
- license key for LT build / advanced features:
BeginBatch/EndBatch
GeneratePdfFromFiles
overload that accepts WkHtmlInput parameters
- email support/assistance (support is NOT available for free users)
- c# examples (listed above)
- usage conditions remain the same as for free users
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:
Legacy .NET Framework 2.0 and 4.0 runtimes are supported.
.NET Core
NReco.PdfGenerator.LT nuget package includes netstandard20 build and fully compatible with .NET Core 2.x & 3.x apps.
Note: you need to deploy wkhtmltopdf binaries for your target platform(s) (Windows, Linux or OS X) with your .NET Core app. It is possible to include wkhtmltopdf into AWS Lambda function with this instruction.
Legacy windows versions (XP/2003 Server)
NReco.PdfGenerator nuget package embeds windows build of wkhtmltopdf.exe (MSVC 2015) and it can work only on Windows Vista/2008 R2 or newer.
For older Windows versions NReco.PdfGenerator.LT should be used with MinGW-build of wkhtmltopdf.
LT build usage
The following C# code snippet illustrates how to initialize LT build:
Component cannot be used (does not work) in the following cases:
- partial-trust environments where starting new processes is prohibited (shared ASP.NET hostings)
- Windows Servers with restricted access to GDI API: Azure Apps (Free/Shared subscriptions) are NOT supported.
Azure Apps VM-based plans (Basic, Standard, Premium) can use NReco.PdfGenerator with some limitations (custom fonts are not loaded on Azure Apps Windows). - .NET platforms where System.Diagnostics.Process API is not available (like UWP/Univeral Apps)
Legacy .NET Framework 2.0 and 4.0 runtimes are supported.
.NET Core
NReco.PdfGenerator.LT nuget package includes netstandard20 build and fully compatible with .NET Core 2.x & 3.x apps.
Note: you need to deploy wkhtmltopdf binaries for your target platform(s) (Windows, Linux or OS X) with your .NET Core app. It is possible to include wkhtmltopdf into AWS Lambda function with this instruction.
Legacy windows versions (XP/2003 Server)
NReco.PdfGenerator nuget package embeds windows build of wkhtmltopdf.exe (MSVC 2015) and it can work only on Windows Vista/2008 R2 or newer.
For older Windows versions NReco.PdfGenerator.LT should be used with MinGW-build of wkhtmltopdf.
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
forTR
,TH
,TD
.
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
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
There are 2 ways how ASPX page can be exported to PDF:
- use GeneratePdfFromFile method and specify absolute URL to ASPX page as input file path (simplest solution if ASPX page is doesn't require authentication).
- 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(strWr); 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.
This is known wkhtmltopdf 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).
what's new
2020 Jun 13 |
v.1.2.0 changes:
|
2017 Mar 30 |
v.1.1.15 changes:
|
2017 Feb 18 |
v.1.1.14 changes:
|
2016 Feb 03 |
v.1.1.12 changes:
|
2015 Dec 06 |
v.1.1.11 changes:
|
2015 Oct 01 |
v.1.1.10 changes:
|
2015 Aug 29 |
v.1.1.9 changes:
|
2015 Jul 02 |
v.1.1.7 changes:
|
2015 Mar 03 |
v.1.1.6 changes:
|
2015 Feb 06 |
v.1.1.4 + v.1.1.5 changes:
|
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).