Menu

EO.Pdf by Essential Objects – Extending to include ASP.net cookie authentication

Problem

EO.Pdf  has its own internal browser to generate the PDF, therefore ASP.net /MVC cookies are not shared across EO.Pdf  and ASP.net. When you ret to generate PDF using HtmlToPdf.ConvertUrl(“your url”,pdfDocument); you will probably get your unauthorised page or Login page in the PDF that is generated.

Solution

The solution is to add asp.net/mvc cookie to HtmlToPdfOptions. Wrote an extension method include the cookies, like below

public static class HtmlToPdfOptionsExtensions
    {
        public static void AddAuthenticationCookies(this HtmlToPdfOptions pdf, HttpCookieCollection cookies)
        {
            var authCookies = cookies.AllKeys.Distinct().Where(k => !k.Contains("Authentication"));
            foreach (var key in authCookies)
            {
                if (!string.IsNullOrEmpty(cookies[key].Value))
                    pdf.Cookies.Add(new System.Net.Cookie(key, cookies[key].Value));
            }
        }
    }

in your PDF generation code you can use it like below

var pdfDocument = new PdfDocument();
//.... any other PDF options
HtmlToPdf.Options.AddAuthenticationCookies(Request.Cookies);
HtmlToPdf.ConvertUrl(reportUrl, pdfDocument);
//.... rest of the code to out put PDF

 

Leave a comment