ASP.NET MVC – Pdf View

by Svetlozar Angelov 1. February 2010 11:49

Here is an example how you can return a pdf response in a asp.net mvc project. First of all you need a FileStreamResultmethod in your controller(it handles the pdf request).

public FileStreamResult PdfViewDemo()
{
    Stream Pdf = //code that returns pdf stream
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=pdfexample.pdf");
    return new FileStreamResult(Pdf, "application/pdf"); 
}  

I’m going to implement a simple pdf load from the hard drive, but the more powerful approach is to generate your pdf “on the fly” using library such as ITextSharp.

public class ReportsHelper
{
    public Stream GeneratePdf()
    {
        FileStream inputPdf = File.OpenRead("C:\\YourPath\SomePdf.pdf");
        MemoryStream ms = new MemoryStream();
        ms.SetLength(inputPdf.Length);
        inputPdf.Read(ms.GetBuffer(), 0, (int)inputPdf.Length);
        return ms;
    }
}   //end ReportsHelper class

and the FileStreamResult method becomes

public FileStreamResult PdfViewDemo() 
{
    ReportsHelper repHelper = new ReportsHelper();
    Stream Pdf = repHelper.GeneratePdf();
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=pdfexample.pdf");
    return new FileStreamResult(Pdf, "application/pdf"); 
}   

Tags: ,

programming

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen