2

I want to be able to render a PDF from an action in my C#.NET MVC application using .NET Identity.

However, the Action I want to render requires the user to be authenticated and HiQPdf doesn't respect cookies as-is.

How can I achieve this?

karlingen
  • 13,800
  • 5
  • 43
  • 74
  • 1
    Just to head off more flagging: **self-answering is not only permitted but [specifically encouraged](https://stackoverflow.com/help/self-answer)**. Please do not flag such posts for moderator attention, and do not berate the author for having used a feature that is specifically designed to share knowledge. – Martijn Pieters Oct 16 '17 at 12:35

1 Answers1

2

You need to pass cookies to the pdf generator and the rest should work:

public ActionResult DownloadPdf(int? id)
{
    var fullUrl = Url.Action("Details", "MyController", new { id }, Request.Url.Scheme);
    var pdf = new HtmlToPdf();
    string fileName = "Some name.pdf";
    var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
    foreach(var cookie in cookies)
        pdf.HttpCookies.AddCookie(cookie.Key,cookie.Value);

    return File(pdf.ConvertUrlToMemory(fullUrl), System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
}
karlingen
  • 13,800
  • 5
  • 43
  • 74