This project has moved. For the latest updates, please go here.

Convert HTML to PDF in ASP.NET and MVC with C# using a Free HTML to PDF Converter for .NET

This ASP.NET C# example project uses Free HiQPdf HTML to PDF Converter Library for .NET to show you how to convert HTML pages and HTML code to PDF in your .NET applications. The HiQPdf HTML to PDF Converter for .NET is a fast method to easily create richly-formatted PDF documents in your .NET applications from HTML documents and web pages.

Download Free HTML to PDF Converter for .NET Zip Package 

The majority of the websites are already able to produce reports or to present various results in HTML pages but while the HTML content is simple to generate, edit and display it is not suitable for printing or for transmission by email. The HTML to PDF Converter for .NET can accurately convert HTML pages to PDF documents in your ASP.NET websites and .NET desktop applications in just a few lines of C# or VB.NET code.

C# Sample Code for ASP.NET

The sample is an ASP.NET website in C# offering sample code for the most important features of the software. To build the sample you have to open the Visual Studio solution and build the project. The Visual Studio project references the Free HTML to PDF for .NET Package from NuGet and will be automatically copied from there to your local folder when the project is built. After build you can run the demo application in a browser. The sample for the fully featured version of the software is available online at HiQPdf HTML to PDF Demo where you can find more examples.

This example shows how easy you can create the PDF documents from existing HTML pages or HTML strings. The HTML page can contain HTML5 code, CSS3, JavaScript or SVG. With just a few lines of code you can get complex PDF document.

In the code sample below you can learn how to set the internal browser width and height, similar to the window width of a browser, set the generated PDF page size, orientation and margins. When you convert a HTML string containing relative URLs to images, CSS and JavaScript files you also have to specify a base URL to resolve these resources.

protected void buttonConvertToPdf_Click(object sender, EventArgs e) 
{ 
    // create the HTML to PDF converter 
    HtmlToPdf htmlToPdfConverter = new HtmlToPdf(); 
 
    // set browser width 
    htmlToPdfConverter.BrowserWidth = int.Parse(textBoxBrowserWidth.Text); 
 
    // set browser height if specified, otherwise use the default 
    if (textBoxBrowserHeight.Text.Length > 0) 
        htmlToPdfConverter.BrowserHeight = int.Parse(textBoxBrowserHeight.Text); 
 
    // set HTML Load timeout 
    htmlToPdfConverter.HtmlLoadedTimeout = int.Parse(textBoxLoadHtmlTimeout.Text); 
 
    // set PDF page size and orientation 
    htmlToPdfConverter.Document.PageSize = GetSelectedPageSize(); 
    htmlToPdfConverter.Document.PageOrientation = GetSelectedPageOrientation(); 
 
    // set PDF page margins 
    htmlToPdfConverter.Document.Margins = new PdfMargins(0); 
 
    // set a wait time before starting the conversion 
    htmlToPdfConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text); 
 
    // convert HTML to PDF 
    byte[] pdfBuffer = null; 
 
    if (radioButtonConvertUrl.Checked) 
    { 
        // convert URL to a PDF memory buffer 
        string url = textBoxUrl.Text; 
 
        pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url); 
    } 
    else 
    { 
        // convert HTML code 
        string htmlCode = textBoxHtmlCode.Text; 
        string baseUrl = textBoxBaseUrl.Text; 
 
        // convert HTML code to a PDF memory buffer 
        pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, baseUrl); 
    } 
 
    // inform the browser about the binary data format 
    HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf"); 
 
    // instruct browser how to open PDF as attachment or inline and file name 
    HttpContext.Current.Response.AddHeader("Content-Disposition", 
String.Format("{0}; filename=HtmlToPdf.pdf; size={1}", checkBoxOpenInline.Checked ? "inline" : "attachment",
pdfBuffer.Length.ToString())); // write the PDF buffer to HTTP response HttpContext.Current.Response.BinaryWrite(pdfBuffer); // call End() method of HTTP response to stop ASP.NET page processing HttpContext.Current.Response.End(); }

C# Sample Code for MVC

When you convert an ASP.NET MVC URL, the converter will make a GET request to the URL in a new session and the values stored in the current ASP.NET Session are not available. The solution is to get the HTML code rendered by the MVC view in the current context of the MVC controller and to convert that HTML code to PDF giving the appropriate base URL. 


The sample code below demonstrates this solution. When the 'Convert This Page to PDF' button in the Index view is pressed the Index view itself is converted. When the 'Convert About Page to PDF' button in the Index view is pressed the About view in the same application is converted to PDF.

public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
Session["MySessionVariable"] = "My Session Variable Value assigned in Index";

return View();
}

public string RenderViewAsString(string viewName, object model)
{
// create a string writer to receive the HTML code
StringWriter stringWriter = new StringWriter();

// get the view to render
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext,
viewName, null);
// create a context to render a view based on a model
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
new ViewDataDictionary(model),
new TempDataDictionary(),
stringWriter
);

// render the view to a HTML code
viewResult.View.Render(viewContext, stringWriter);

// return the HTML code
return stringWriter.ToString();
}

[HttpPost]
public ActionResult ConvertHtmlPageToPdf()
{
// get the HTML code of this view
string htmlToConvert = RenderViewAsString("Index", null);

// the base URL to resolve relative images and css
String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = thisPageUrl.Substring(0, thisPageUrl.Length -
"Home/ConvertThisPageToPdf".Length);

// instantiate the HiQPdf HTML to PDF converter
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

// hide the button in the created PDF
htmlToPdfConverter.HiddenHtmlElements = new string[]
{ "#convertThisPageButtonDiv" };

// render the HTML code as PDF in memory
byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);

// send the PDF file to browser
FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
fileResult.FileDownloadName = "ThisMvcViewToPdf.pdf";

return fileResult;
}
}

Free HTML to PDF Converter for .NET Features

  • Convert HTML and HTML5 Documents and Web Pages to PDF
  • Convert URLs and HTML Strings to PDF Files or Memory Buffers
  • Set the PDF Page Size and Orientation
  • Fit HTML Content in PDF Page Size
  • Advanced Support for Web Fonts in .WOFF and .TTF Formats
  • Advanced Support for Scalar Vector Graphics (SVG)
  • Advanced Support for HTML5 and CSS3
  • Delayed Conversion Triggering Mode
  • Control PDF page breaks with page-break CSS attributes in HTML
  • Repeat HTML Table Header and Footer on Each PDF Page
  • Create up to three PDF pages of high quality content for free
  • Packaged and Delivered as a Zip Archive
  • No External Dependencies
  • Direct Copy Deployment Supported
  • ASP.NET, MVC and Windows Forms Samples in C# and VB.NET
  • Fully documented .NET API with examples
  • Supported on All Windows Versions and in Azure cloud services

Using the HTML to PDF Library in your .NET Applications

The integration of the Free HTML to PDF Converter for .NET Library in your own ASP.NET and MVC application is very simple. You just have to add a reference to the NuGet package in your Visual Studio project. For this you can right click on References in project and select Manage NuGet Packages then search the nuget.org for HiQPdf packages and select the free version of the package. Now you are ready to use the converter in your code. Copy the sample C# code above in your application and rebuild you project.

More Information

The  Free HTML to PDF Converter Library for .NET which is the limited free version of the full HiQPdf HTML to PDF Library for .NET. With this free version you can create maximum 3 PDF pages of high quality content. There are also some advanced features like live URLs, internal links, outlines, PDF forms, table of contents, edit, merge and split PDF documents, extract text and images from PDF or PDF pages rasterization which are available only in the full version of the software. You can read more about the software on HiQPdf HTML to PDF for .NET Blog page.

 

Last edited Dec 29, 2016 at 12:53 PM by hiqpdf, version 40