1

I just want to generate a pdf document of the details presents in view on button click.

Sonam Mohite
  • 885
  • 4
  • 19
  • 51
  • possible duplicate of [Asp.Net MVC how to get view to generate PDF](http://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf) – Rafay Mar 02 '12 at 05:34

1 Answers1

2

In order to generate a PDF file you will need some third party library as this functionality is not built-in the .NET framework. iTextSharp is a popular one.

So for example you could write a custom action result:

public class PdfResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/pdf";
        var cd = new ContentDisposition
        {
            Inline = true,
            FileName = "test.pdf",
        };
        response.AddHeader("Content-Disposition", cd.ToString());

        using (var doc = new Document())
        using (var writer = PdfWriter.GetInstance(doc, response.OutputStream))
        {
            doc.Open();
            doc.Add(new Phrase("Hello World"));
        }
    }
}

and then have your controller action return this result:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return new PdfResult();
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin for great support. This code is too easy to understand and implement. – Sonam Mohite Mar 02 '12 at 08:40
  • Hey Darin can you please tell me that how to show information about a student from particular class in PDF file, as like report. – Sonam Mohite Mar 02 '12 at 09:03
  • @SonamMohite, that will depend on how you want to format the data. I would recommend you starting a new question specific to iTextSharp this time in which you present and explain exactly how the report must look like, what data source do you have as input and of course the desired output. – Darin Dimitrov Mar 02 '12 at 11:06
  • I put in this code, and it seems to return the data if I look in fiddler. It is however not triggering the download on the browser. How do get it to do that? – jmogera Feb 20 '13 at 15:06
  • @jmogera, Set `Inline = false` in the ContentDisposition. – Darin Dimitrov Feb 20 '13 at 15:11