[c#] Convert HTML to PDF in .NET

I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout just gets messy.

Is there a better way?

This question is related to c# html pdf itextsharp

The answer is


I'm the author of the Rotativa package. It allows to create PDF files directly from razor views:

https://www.nuget.org/packages/Rotativa/

Trivial to use and you have full control on the layout since you can use razor views with data from your Model and ViewBag container.

I developed a SaaS version on Azure. It makes it even easier to use it from WebApi or any .Net app, service, Azure website, Azure webjob, whatever runs .Net.

http://www.rotativahq.com/

Free accounts available.


There's also a new web-based document generation app - DocRaptor.com. Seems easy to use, and there's a free option.


Last Updated: October 2020

This is the list of options for HTML to PDF conversion in .NET that I have put together (some free some paid)

If none of the options above help you you can always search the NuGet packages:
https://www.nuget.org/packages?q=html+pdf


Below is an example of converting html + css to PDF using iTextSharp (iTextSharp + itextsharp.xmlworker)

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;


byte[] pdf; // result will be here

var cssText = File.ReadAllText(MapPath("~/css/test.css"));
var html = File.ReadAllText(MapPath("~/css/test.html"));

using (var memoryStream = new MemoryStream())
{
        var document = new Document(PageSize.A4, 50, 50, 60, 60);
        var writer = PdfWriter.GetInstance(document, memoryStream);
        document.Open();

        using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
        {
            using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
            {
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
            }
        }

        document.Close();

        pdf = memoryStream.ToArray();
}

Best Tool i have found and used for generating PDF of javascript and styles rendered views or html pages is phantomJS.

Download the .exe file with the rasterize.js function found in root of exe of example folder and put inside solution.

It Even allows you to download the file in any code without opening that file also it also allows to download the file when the styles and specially jquery are applied.

Following code generate PDF File :

public ActionResult DownloadHighChartHtml()
{
    string serverPath = Server.MapPath("~/phantomjs/");
    string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";
    string Url = "http://wwwabc.com";

    new Thread(new ParameterizedThreadStart(x =>
    {
        ExecuteCommand(string.Format("cd {0} & E: & phantomjs rasterize.js {1} {2} \"A4\"", serverPath, Url, filename));
                           //E: is the drive for server.mappath
    })).Start();

    var filePath = Path.Combine(Server.MapPath("~/phantomjs/"), filename);

    var stream = new MemoryStream();
    byte[] bytes = DoWhile(filePath);

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Image.pdf");
    Response.OutputStream.Write(bytes, 0, bytes.Length);
    Response.End();
    return RedirectToAction("HighChart");
}



private void ExecuteCommand(string Command)
{
    try
    {
        ProcessStartInfo ProcessInfo;
        Process Process;

        ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);

        ProcessInfo.CreateNoWindow = true;
        ProcessInfo.UseShellExecute = false;

        Process = Process.Start(ProcessInfo);
    }
    catch { }
}


private byte[] DoWhile(string filePath)
{
    byte[] bytes = new byte[0];
    bool fail = true;

    while (fail)
    {
        try
        {
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                bytes = new byte[file.Length];
                file.Read(bytes, 0, (int)file.Length);
            }

            fail = false;
        }
        catch
        {
            Thread.Sleep(1000);
        }
    }

    System.IO.File.Delete(filePath);
    return bytes;
}

I found the following library more effective in converting html to pdf.
nuget: https://www.nuget.org/packages/Select.HtmlToPdf/


PDFmyURL recently released a .NET component for web page / HTML to PDF conversion as well. This has a very user friendly interface, for example:

PDFmyURL pdf = new PDFmyURL("yourlicensekey");
pdf.ConvertURL("http://www.example.com", Application.StartupPath + @"\example.pdf");

Documentation: PDFmyURL .NET component documentation

Disclaimer: I work for the company that owns PDFmyURL


I recently performed a PoC regarding HTML to PDF conversion and wanted to share my results.

My favorite by far is OpenHtmlToPdf

Advantages of this tool:

  • Very good HTML compatibility (e.g. it was the only tool in my example that correctly repeated table headers when a table spanned multiple pages)
  • Fluent API
  • Free and OpenSource (Creative Commons Attribution 3.0 license)
  • Available via NuGet

Other tools tested:


If you want user to download the pdf of rendered page in the browser then the easiest solution to the problem is

window.print(); 

on client side it will prompt user to save pdf of current page. You can also customize the appearance of pdf by linking style

<link rel="stylesheet" type="text/css" href="print.css" media="print">

print.css is applied to the html while printing.

Limitation

You can't store the file on server side. User prompt to print the page than he had to save page manually. Page must to be rendered in a tab.


Quite likely most projects will wrap a C/C++ Engine rather than implementing a C# solution from scratch. Try Project Gotenberg.

To test it

docker run --rm -p 3000:3000 thecodingmachine/gotenberg:6

Curl sample

curl --request POST \
    --url http://localhost:3000/convert/url \
    --header 'Content-Type: multipart/form-data' \
    --form remoteURL=https://brave.com \
    --form marginTop=0 \
    --form marginBottom=0 \
    --form marginLeft=0 \
    --form marginRight=0 \
    -o result.pdf

C# sample.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using static System.Console;

namespace Gotenberg
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            try
            {
                var client = new HttpClient();            
                var formContent = new MultipartFormDataContent
                    {
                        {new StringContent("https://brave.com/"), "remoteURL"},
                        {new StringContent("0"), "marginTop" }
                    };
                var result = await client.PostAsync(new Uri("http://localhost:3000/convert/url"), formContent);
                await File.WriteAllBytesAsync("duckduck.com.pdf", await result.Content.ReadAsByteArrayAsync());
            }
            catch (Exception ex)
            {
                WriteLine(ex);
            }
        }
    }
}

To compile

csc sample.cs -langversion:latest -reference:System.Net.Http.dll && mono ./sample.exe

Ok, using this technologies....

The src can be downloaded from here it needs nant


You can use Google Chrome print-to-pdf feature from its headless mode. I found this to be the simplest yet the most robust method.

var url = "https://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net";
var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
var output = Path.Combine(Environment.CurrentDirectory, "printout.pdf");
using (var p = new Process())
    {
        p.StartInfo.FileName = chromePath;
        p.StartInfo.Arguments = $"--headless --disable-gpu --print-to-pdf={output} {url}";
        p.Start();
        p.WaitForExit();
    }


Update: I would now recommend PupeteerSharp over wkhtmltopdf.

Try wkhtmtopdf. It is the best tool I have found so far.

For .NET, you may use this small library to easily invoke wkhtmtopdf command line utility.


I highly recommend NReco, seriously. It has the free and paid version, and really worth it. It uses wkhtmtopdf in background, but you just need one assembly. Fantastic.

Example of use:

Install via NuGet.

var htmlContent = String.Format("<body>Hello world: {0}</body>", DateTime.Now);
var pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);

Disclaimer: I'm not the developer, just a fan of the project :)


ABCpdf.NET (http://www.websupergoo.com/abcpdf-5.htm)

We use and recommend.

Very good component, it not only convert a webpage to PDF like an image but really convert text, image, formatting, etc...

It's not free but it's cheap.


You need to use a commercial library if you need perfect html rendering in pdf.

ExpertPdf Html To Pdf Converter is very easy to use and it supports the latest html5/css3. You can either convert an entire url to pdf:

using ExpertPdf.HtmlToPdf; 
byte[] pdfBytes = new PdfConverter().GetPdfBytesFromUrl(url);

or a html string:

using ExpertPdf.HtmlToPdf; 
byte[] pdfBytes = new PdfConverter().GetPdfBytesFromHtmlString(html, baseUrl);

You also have the alternative to directly save the generated pdf document to a Stream of file on the disk.


I was also looking for this a while back. I ran into HTMLDOC http://www.easysw.com/htmldoc/ which is a free open source command line app that takes an HTML file as an argument and spits out a PDF from it. It's worked for me pretty well for my side project, but it all depends on what you actually need.

The company that makes it sells the compiled binaries, but you are free to download and compile from source and use it for free. I managed to compile a pretty recent revision (for version 1.9) and I intend on releasing a binary installer for it in a few days, so if you're interested I can provide a link to it as soon as I post it.

Edit (2/25/2014): Seems like the docs and site moved to http://www.msweet.org/projects.php?Z1


If you don't really need a true .Net PDF library, there are numerous free HTML to PDF tools, many of which can run from a command-line.

One solution would be to pick one of those and then write a thin wrapper around that in C#. E.g., as done in this tutorial.


2018's update, and Let's use standard HTML+CSS=PDF equation!

There are good news for HTML-to-PDF demands. As this answer showed, the W3C standard css-break-3 will solve the problem... It is a Candidate Recommendation with plan to turn into definitive Recommendation in 2017 or 2018, after tests.

As not-so-standard there are solutions, with plugins for C#, as showed by print-css.rocks.


Winnovative offer a .Net PDF library that supports HTML input. They offer an unlimited free trial. Depending on how you wish to deploy your project, this might be sufficient.


Another suggestion it to try the solution by https://grabz.it.

They provide a nice .NET API to catch screenshots and manipulate it in an easy and flexible approach.

To use it in your app you will need to first get key + secret and download the .NET SDK (it's free).

Now a short example of using it.

To use the API you will first need to create an instance of the GrabzItClient class, passing your application key and application secret from your GrabzIt account to the constructor, as shown in the below example:

//Create the GrabzItClient class
//Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!
private GrabzItClient grabzIt = GrabzItClient.Create("Sign in to view your Application Key", "Sign in to view your Application Secret");

Now, to convert the HTML to PDF all you need to do it:

grabzIt.HTMLToPDF("<html><body><h1>Hello World!</h1></body></html>");

You can convert to image as well:

grabzIt.HTMLToImage("<html><body><h1>Hello World!</h1></body></html>");     

Next you need to save the image. You can use one of the two save methods available, Save if publicly accessible callback handle available and SaveTo if not. Check the documentation for details.


Instead of parsing HTML directly to PDF, you can create an Bitmap of your HTML-page and then insert the Bitmap into your PDF, using for example iTextSharp.

Here's a code how to get an Bitmap of an URL. I found it somewhere here on SO, if I find the source I'll link it.

public System.Drawing.Bitmap HTMLToImage(String strHTML)
{
    System.Drawing.Bitmap myBitmap = null;

    System.Threading.Thread myThread = new System.Threading.Thread(delegate()
    {
        // create a hidden web browser, which will navigate to the page
        System.Windows.Forms.WebBrowser myWebBrowser = new System.Windows.Forms.WebBrowser();
        // we don't want scrollbars on our image
        myWebBrowser.ScrollBarsEnabled = false;
        // don't let any errors shine through
        myWebBrowser.ScriptErrorsSuppressed = true;
        // let's load up that page!    
        myWebBrowser.Navigate("about:blank");

        // wait until the page is fully loaded
        while (myWebBrowser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
            System.Windows.Forms.Application.DoEvents();

        myWebBrowser.Document.Body.InnerHtml = strHTML;

        // set the size of our web browser to be the same size as the page
        int intScrollPadding = 20;
        int intDocumentWidth = myWebBrowser.Document.Body.ScrollRectangle.Width + intScrollPadding;
        int intDocumentHeight = myWebBrowser.Document.Body.ScrollRectangle.Height + intScrollPadding;
        myWebBrowser.Width = intDocumentWidth;
        myWebBrowser.Height = intDocumentHeight;
        // a bitmap that we will draw to
        myBitmap = new System.Drawing.Bitmap(intDocumentWidth - intScrollPadding, intDocumentHeight - intScrollPadding);
        // draw the web browser to the bitmap
        myWebBrowser.DrawToBitmap(myBitmap, new System.Drawing.Rectangle(0, 0, intDocumentWidth - intScrollPadding, intDocumentHeight - intScrollPadding));
    });
    myThread.SetApartmentState(System.Threading.ApartmentState.STA);
    myThread.Start();
    myThread.Join();

    return myBitmap;
}

You can also check Spire, it allow you to create HTML to PDF with this simple piece of code

 string htmlCode = "<p>This is a p tag</p>";

//use single thread to generate the pdf from above html code
Thread thread = new Thread(() =>
{ pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

// Save the file to PDF and preview it.
pdf.SaveToFile("output.pdf");
System.Diagnostics.Process.Start("output.pdf");

Detailed article : How to convert HTML to PDF in asp.net C#


It depends on any other requirements you have.

A really simple but not easily deployable solution is to use a WebBrowser control to load the Html and then using the Print method printing to a locally installed PDF printer. There are several free PDF printers available and the WebBrowser control is a part of the .Net framework.

EDIT: If you Html is XHtml you can use PDFizer to do the job.


Essential PDF can be used to convert HTML to PDF: C# sample. The sample linked to here is ASP.NET based, but the library can be used from Windows Forms, WPF, ASP.NET Webforms, and ASP.NET MVC. The library offers the option of using different HTML rendering engines : Internet Explorer (default) and WebKit (best output).

The whole suite of controls is available for free (commercial applications also) through the community license program if you qualify. The community license is the full product with no limitations or watermarks.

Note: I work for Syncfusion.


EDIT: New Suggestion HTML Renderer for PDF using PdfSharp

(After trying wkhtmltopdf and suggesting to avoid it)

HtmlRenderer.PdfSharp is a 100% fully C# managed code, easy to use, thread safe and most importantly FREE (New BSD License) solution.

Usage

  1. Download HtmlRenderer.PdfSharp nuget package.
  2. Use Example Method.

    public static Byte[] PdfSharpConvert(String html)
    {
        Byte[] res = null;
        using (MemoryStream ms = new MemoryStream())
        {
            var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
            pdf.Save(ms);
            res = ms.ToArray();
        }
        return res;
    }
    

A very Good Alternate Is a Free Version of iTextSharp

Until version 4.1.6 iTextSharp was licensed under the LGPL licence and versions until 4.16 (or there may be also forks) are available as packages and can be freely used. Of course someone can use the continued 5+ paid version.

I tried to integrate wkhtmltopdf solutions on my project and had a bunch of hurdles.

I personally would avoid using wkhtmltopdf - based solutions on Hosted Enterprise applications for the following reasons.

  1. First of all wkhtmltopdf is C++ implemented not C#, and you will experience various problems embedding it within your C# code, especially while switching between 32bit and 64bit builds of your project. Had to try several workarounds including conditional project building etc. etc. just to avoid "invalid format exceptions" on different machines.
  2. If you manage your own virtual machine its ok. But if your project is running within a constrained environment like (Azure (Actually is impossible withing azure as mentioned by the TuesPenchin author) , Elastic Beanstalk etc) it's a nightmare to configure that environment only for wkhtmltopdf to work.
  3. wkhtmltopdf is creating files within your server so you have to manage user permissions and grant "write" access to where wkhtmltopdf is running.
  4. Wkhtmltopdf is running as a standalone application, so its not managed by your IIS application pool. So you have to either host it as a service on another machine or you will experience processing spikes and memory consumption within your production server.
  5. It uses temp files to generate the pdf, and in cases Like AWS EC2 which has really slow disk i/o it is a big performance problem.
  6. The most hated "Unable to load DLL 'wkhtmltox.dll'" error reported by many users.

--- PRE Edit Section ---

For anyone who want to generate pdf from html in simpler applications / environments I leave my old post as suggestion.

TuesPechkin

https://www.nuget.org/packages/TuesPechkin/

or Especially For MVC Web Applications (But I think you may use it in any .net application)

Rotativa

https://www.nuget.org/packages/Rotativa/

They both utilize the wkhtmtopdf binary for converting html to pdf. Which uses the webkit engine for rendering the pages so it can also parse css style sheets.

They provide easy to use seamless integration with C#.

Rotativa can also generate directly PDFs from any Razor View.

Additionally for real world web applications they also manage thread safety etc...


Most HTML to PDF converter relies on IE to do the HTML parsing and rendering. This can break when user updates their IE. Here is one that does not rely on IE.

The code is something like this:

EO.Pdf.HtmlToPdf.ConvertHtml(htmlText, pdfFileName);

Like many other converters, you can pass text, file name, or Url. The result can be saved into a file or a stream.


I used ExpertPDF Html To Pdf Converter. Does a decent job. Unfortunatelly, it's not free.


Another trick you can use WebBrowser control, below is my full working code

Assigning Url to text box control in my case

  protected void Page_Load(object sender, EventArgs e)
{

   txtweburl.Text = "https://www.google.com/";

 }

Below is code for generate screeen using thread

  protected void btnscreenshot_click(object sender, EventArgs e)
  {
    //  btnscreenshot.Visible = false;
    allpanels.Visible = true;
    Thread thread = new Thread(GenerateThumbnail);
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();

}

private void GenerateThumbnail()
{
    //  btnscreenshot.Visible = false;
    WebBrowser webrowse = new WebBrowser();
    webrowse.ScrollBarsEnabled = false;
    webrowse.AllowNavigation = true;
    string url = txtweburl.Text.Trim();
    webrowse.Navigate(url);
    webrowse.Width = 1400;
    webrowse.Height = 50000;

    webrowse.DocumentCompleted += webbrowse_DocumentCompleted;
    while (webrowse.ReadyState != WebBrowserReadyState.Complete)
    {
        System.Windows.Forms.Application.DoEvents();
    }
}

In below code I am saving the pdf file after download

        private void webbrowse_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // btnscreenshot.Visible = false;
    string folderPath = Server.MapPath("~/ImageFiles/");

    WebBrowser webrowse = sender as WebBrowser;
    //Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height);

    Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height, PixelFormat.Format16bppRgb565);

    webrowse.DrawToBitmap(bitmap, webrowse.Bounds);


    string Systemimagedownloadpath = System.Configuration.ConfigurationManager.AppSettings["Systemimagedownloadpath"].ToString();
    string fullOutputPath = Systemimagedownloadpath + Request.QueryString["VisitedId"].ToString() + ".png";
    MemoryStream stream = new MemoryStream();
    bitmap.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Jpeg);



    //generating pdf code 
     Document pdfDoc = new Document(new iTextSharp.text.Rectangle(1100f, 20000.25f));
     PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
     pdfDoc.Open();
     iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(fullOutputPath);   
     img.ScaleAbsoluteHeight(20000);
     img.ScaleAbsoluteWidth(1024);     
     pdfDoc.Add(img);
     pdfDoc.Close();
     //Download the PDF file.
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-disposition", "attachment;filename=ImageExport.pdf");
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     Response.Write(pdfDoc);
     Response.End();


}

You can also refer my oldest post for more information: Navigation to the webpage was canceled getting message in asp.net web form


Try this PDF Duo .Net converting component for converting HTML to PDF from ASP.NET application without using additional dlls.

You can pass the HTML string or file, or stream to generate the PDF. Use the code below (Example C#):

string file_html = @"K:\hdoc.html";   
string file_pdf = @"K:\new.pdf";   
try   
{   
    DuoDimension.HtmlToPdf conv = new DuoDimension.HtmlToPdf();   
    conv.OpenHTML(file_html);   
    conv.SavePDF(file_pdf);   
    textBox4.Text = "C# Example: Converting succeeded";   
}   

Info + C#/VB examples you can find at: http://www.duodimension.com/html_pdf_asp.net/component_html_pdf.aspx


It seems like so far the best free .NET solution is the TuesPechkin library which is a wrapper around the wkhtmltopdf native library.

I've now used the single-threaded version to convert a few thousand HTML strings to PDF files and it seems to work great. It's supposed to also work in multi-threaded environments (IIS, for example) but I haven't tested that.

Also since I wanted to use the latest version of wkhtmltopdf (0.12.5 at the time of writing), I downloaded the DLL from the official website, copied it to my project root, set copy to output to true, and initialized the library like so:

var dllDir = AppDomain.CurrentDomain.BaseDirectory;
Converter = new StandardConverter(new PdfToolset(new StaticDeployment(dllDir)));

Above code will look exactly for "wkhtmltox.dll", so don't rename the file. I used the 64-bit version of the DLL.

Make sure you read the instructions for multi-threaded environments, as you will have to initialize it only once per app lifecycle so you'll need to put it in a singleton or something.


PDF Vision is good. However, you have to have Full Trust to use it. I already emailed and asked why my HTML wasn't being converted on the server but it worked fine on localhost.


To convert HTML to PDF in C# use ABCpdf.

ABCpdf can make use of the Gecko or Trident rendering engines, so your HTML table will look the same as it appears in FireFox and Internet Explorer.

There's an on-line demo of ABCpdf at www.abcpdfeditor.com. You could use this to check out how your tables will render first, without needing to download and install software.

For rendering entire web pages you'll need the AddImageUrl or AddImageHtml functions. But if all you want to do is simply add HTML styled text then you could try the AddHtml function, as below:

Doc theDoc = new Doc();
theDoc.FontSize = 72;
theDoc.AddHtml("<b>Some HTML styled text</b>");
theDoc.Save(Server.MapPath("docaddhtml.pdf"));
theDoc.Clear();

ABCpdf is a commercial software title, however the standard edition can often be obtained for free under special offer.


Already if you are using itextsharp dll, no need to add third party dll's(plugin), I think you are using htmlworker instead of it use xmlworker you can easily convert your html to pdf.

Some css won't work they are Supported CSS
Full Explain with example Reference Click here


        MemoryStream memStream = new MemoryStream();
        TextReader xmlString = new StringReader(outXml);
        using (Document document = new Document())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, memStream);
            //document.SetPageSize(iTextSharp.text.PageSize.A4);
            document.Open();
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(outXml);
            MemoryStream ms = new MemoryStream(byteArray);
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, ms, System.Text.Encoding.UTF8);
            document.Close();
        }

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(memStream.ToArray());
        Response.End();
        Response.Flush();

As a representative of HiQPdf Software I believe the best solution is HiQPdf HTML to PDF converter for .NET. It contains the most advanced HTML5, CSS3, SVG and JavaScript rendering engine on market. There is also a free version of the HTML to PDF library which you can use to produce for free up to 3 PDF pages. The minimal C# code to produce a PDF as a byte[] from a HTML page is:

HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

// set PDF page size, orientation and margins
htmlToPdfConverter.Document.PageSize = PdfPageSize.A4;
htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
htmlToPdfConverter.Document.Margins = new PdfMargins(0);

// convert HTML to PDF 
byte[] pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);

You can find more detailed examples both for ASP.NET and MVC in HiQPdf HTML to PDF Converter examples repository.


Here is a wrapper for wkhtmltopdf.dll by pruiz

And a wrapper for wkhtmltopdf.exe by Codaxy
- also on nuget.


With Winnovative HTML to PDF converter you can convert a HTML string in a single line

byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);

The base URL is used to resolve the images referenced by relative URLs in HTML string. Alternatively you can use full URLs in HTML or embed images using src="data:image/png" for image tag.

In answer to 'fubaar' user comment about Winnovative converter, a correction is necessary. The converter does not use IE as rendering engine. It actually does not depend on any installed software and the rendering is compatible with WebKit engine.


This is a free library and works very easily : OpenHtmlToPdf

string timeStampForPdfName = DateTime.Now.ToString("yyMMddHHmmssff");

string serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/FolderName");
string pdfSavePath = Path.Combine(@serverPath, "FileName" + timeStampForPdfName + ".FileExtension");


//OpenHtmlToPdf Library used for Performing PDF Conversion
var pdf = Pdf.From(HTML_String).Content();

//FOr writing to file from a ByteArray
 File.WriteAllBytes(pdfSavePath, pdf.ToArray()); // Requires System.Linq

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to pdf

ImageMagick security policy 'PDF' blocking conversion How to extract table as text from the PDF using Python? Extract a page from a pdf as a jpeg How can I read pdf in python? Generating a PDF file from React Components Extract Data from PDF and Add to Worksheet How to extract text from a PDF file? How to download PDF automatically using js? Download pdf file using jquery ajax Generate PDF from HTML using pdfMake in Angularjs

Examples related to itextsharp

How to convert HTML to PDF using iTextSharp Add Header and Footer for PDF using iTextsharp how to set width for PdfPCell in ItextSharp Merging multiple PDFs using iTextSharp in c#.net Adding an image to a PDF using iTextSharp and scale it properly ITextSharp HTML to PDF? Reading PDF content with itextsharp dll in VB.NET or C# How to return PDF to browser in MVC? Convert HTML to PDF in .NET