Asp.Net MVC how to get view to generate PDF

Solution 1:

I use iTextSharp to generate dynamic PDF's in MVC. All you need to do is put your PDF into a Stream object and then your ActionResult return a FileStreamResult. I also set the content-disposition so the user can download it.

public FileStreamResult PDFGenerator()
{
    Stream fileStream = GeneratePDF();

    HttpContext.Response.AddHeader("content-disposition", 
    "attachment; filename=form.pdf");

    return new FileStreamResult(fileStream, "application/pdf");
}

I also have code that enables me to take a template PDF, write text and images to it etc (if you wanted to do that).

  • Note: you must set the Stream position to 0.
private Stream GeneratePDF()
{
    //create your pdf and put it into the stream... pdf variable below
    //comes from a class I use to write content to PDF files

    MemoryStream ms = new MemoryStream();

    byte[] byteInfo = pdf.Output();
    ms.Write(byteInfo, 0, byteInfo.Length);
    ms.Position = 0;

    return ms;
}

Solution 2:

our final answer to this problem was to use Rotativa.

It wraps up the WKhtmltopdf.exe like some of the other solutions, but it's by far the easiest to use that I have found

I went and up voted all the other answers that also solve the problem well, but this is what we used to solve the problem posed in the question above. It is different from the other answers.

Here is a Rotativa Tutorial.

after you install it, this is all your need

public ActionResult PrintInvoice(int invoiceId)
{
  return new ActionAsPdf(
                 "Invoice", 
                 new { invoiceId= invoiceId }) 
                 { FileName = "Invoice.pdf" };
}

Very Very simple.

Solution 3:

Creating layout in html and printing afterwards into pdf is the fastest way.

Html into pdf conversion is provided by phantomjs, wkhtmltopdf or jsreport

jsreport provides direct integration with asp.net mvc views, where you can just mark controller action with attribute and it will print pdf instead of html for you.

More on this blog post

Disclaimer: I am the author of jsreport

Solution 4:

This is an old question but one that's still relevant and I thought I'd just share what I've implemented which works well.

  1. Install NuGet package TuesPechkin - a fork in the Pechkin library based on WkHtmlToPdf that uses a Webkit engine to convert HTML pages to PDF.

  2. Write a little helper to read a view and convert it to an HTML string (mvcContext is this.HttpContext). The replace is optional of course!:

    public static string RenderViewToString(HttpContextBase mvcContext, string area, string controllerName, string viewName, object model)
    {
        var context = System.Web.HttpContext.Current;
        var contextBase = mvcContext;
        var routeData = new RouteData();
        if (area == null) area = "";
    
        routeData.DataTokens.Add("area", area);
    
        routeData.Values.Add("controller", controllerName);
    
        var controllerContext = new ControllerContext(contextBase,
                                                routeData,
                                                new EmptyController());
    
        var razorViewEngine = new RazorViewEngine();
        var razorViewResult = razorViewEngine.FindView(controllerContext,
                                                    viewName,
                                                    "",
                                                false);
    
        var writer = new StringWriter();
        var viewContext = new ViewContext(controllerContext,
                                    razorViewResult.View,
                                    new ViewDataDictionary(model),
                                    new TempDataDictionary(),
                                    writer);
        razorViewResult.View.Render(viewContext, writer);
    
        string hostAddress = context.Request.Url.Scheme + "://" + context.Request.Url.Authority;
    
        return writer.ToString()
                     .Replace("src=\"/", "src=\"" + hostAddress + "/")
                     .Replace("<link href=\"/", "<link href=\"" + hostAddress + "/");                         
    }
    
    class EmptyController : ControllerBase
    {
        protected override void ExecuteCore() { }
    }
    

The hard work of the above were from here: http://wouterdekort.blogspot.co.uk/2012/10/rendering-aspnet-mvc-view-to-string-in.html?showComment=1414603363455#c7863520150405064571

  1. Create an MVC Action to generate the document

    public ActionResult DownloadPDF(long CentreID)
    {
        var model = GetModel()
    
        IPechkin converter = Factory.Create();
        byte[] result = converter.Convert(Helpers.PDF.RenderViewToString(this.HttpContext, "area", "controller", "action", model);
        MemoryStream outputStream = new MemoryStream();
        outputStream.Write(result, 0, result.Length);
        outputStream.Position = 0;
    
        return File(outputStream, "application/pdf", "filename.pdf");
    }