Convert an ASP.Net MVC Webpage HTML to PDF

Converting a webpage or plain HTML to PDF helps in sharing the visualized data through different channels like email attachments etc., In this tutorial we are going to see how to convert an ASP.Net MVC Webpage or plain HTML to PDF document. We will use SelectPDF Community edition to convert an ASP.Net MVC View to PDF. There are many other options to convert HTML to PDF, but SelectPDF is easy to integrate with MVC application and its API can handle HTTP Cookies, HTTP Headers etc with good performance.

NOTE: The major limitation I see with SelectPDF community edition is that it limits the PDF generation to 5 pages. SelectPDF offers full featured paid library which has no afore said limitation.

Lets get started by creating an ASP.Net MVC4 application (from Internet application template in Visual Studio). Install SelectPDF community edition nuget using Package Manager Console (of Visual Studio) as shown below.

image

Create below actions. Index action is default action provided by Visual Studio. GetPdf action is used to generate the PDF of Index action using SelectPDF API.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        return View();
    }

    public ActionResult GetPdf()
    {
        var converter = new HtmlToPdf();
        var doc = converter.ConvertUrl("http://localhost:50265/Home/Index");
        doc.Save(System.Web.HttpContext.Current.Response, true, "test.pdf");
        doc.Close();

        return null;
    }
}

As shown in above code, we create an instance of HtmlToPdf() and then call its ConvertUrl(string url) to do the conversion. We write PdfDocument (output of ConvertUrl method) to HttpResponse stream. Finally close the document to release all the resources.

Run the application and navigate to /Home/GetPdf. We should get the PDF document as shown below.

image

Now lets make small changes in Index action to support Session usage.

public ActionResult Index()
{
    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
    Session["Test"] = "Value";
    return View();
}

Make the following change in Index.cshtml to display Session value.

<h3>We suggest the following: @Session["Test"].ToString()</h3>

Now when we navigate to /Home/GetPdf endpoint, we will get PDF generated displaying Session value.

image

Now lets check how to generate PDF of authenticated views (which are protected). As we created this MVC application from Internet application template, default forms authentication will work without any changes. Click on Register link on top of the page and complete registration as shown below.

image

Decorate Home controller with Authorize attribute (as shown below).

[Authorize]
public class HomeController : Controller

Change the GetPdf Action to pass forms authentication cookie to Converter.

public ActionResult GetPdf()
{
    var converter = new HtmlToPdf();
    converter.Options.HttpCookies.Add(
            FormsAuthentication.FormsCookieName,
            Request.Cookies[FormsAuthentication.FormsCookieName].Value);

    var doc = converter.ConvertUrl("http://localhost:50265/Home/Index");
    doc.Save(System.Web.HttpContext.Current.Response, true, "test.pdf");
    doc.Close();

    return null;
}

Run the application and login to the application with above created credentials. Navigate to /Home/GetPdf endpoint, we should be below generated PDF which included login details as well.

image

SelectPDF is also capable of converting HTML string to PDF. To check this functionality, change the GetPdf action as shown below.

public async Task<ActionResult> GetPdf()
{
    var converter = new HtmlToPdf();
    var baseAddress = new Uri("http://localhost:50265");
    var cookieContainer = new CookieContainer();

    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (HttpClient client = new HttpClient(handler) { BaseAddress = baseAddress })
    {
        cookieContainer.Add(baseAddress, new Cookie(FormsAuthentication.FormsCookieName,
            Request.Cookies[FormsAuthentication.FormsCookieName].Value));
        var result = await client.GetAsync("/Home/Index");
        var htmlString = string.Format("{0}{1}", "<div>This is test</div>", await result.Content.ReadAsStringAsync());

        var doc = converter.ConvertHtmlString(htmlString, baseAddress.ToString());
        doc.Save(System.Web.HttpContext.Current.Response, true, "test.pdf");
        doc.Close();
    }
    return null;
}

As shown in above code, we make a web request to /Home/Index endpoint using HttpClient. On successful response, we read the HttpContent as string (plain HTML). Finally pass that HTML string to HtmlToPdf converter along with baseAddress (baseAddress is used by converter to resolve relative URL’s for images, stylesheets etc.,).

NOTE: I added <div>This is Test</div> to demonstrate that we can do string manipulations and it will be included as part of generated PDF.

When we run the application we get the PDF response as shown below.

 image

That’s it for now, Happy Coding and Stay Tuned!!!

You may also like...