I would like to call an action on a controller. Have the controller get the data from the model. The view then runs and generates a PDF. The only example I have found is in an article by Lou http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action. His code is very elegant. The view is using ITextSharp to generate the PDF. The only downside is his example uses the Spark View Engine. Is there a way to do a similar thing with the standard Microsoft view engine?
+26
A:
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; }
David Liddle
2009-04-22 22:19:48
nice code. I was wondering how we could do that.
MikeJ
2009-04-22 22:22:10
Just what I was looking for
borisCallens
2009-07-13 09:29:48
I would love to see example of what that "pdf class" in the example looks like or get some hints on how to implement it?
jesperlind
2009-08-06 23:37:51
The only thing I would add to this is that this Action cannot be called from a partial postback (ajax) but rather use a Html.ActionLink or the like.
zonkflut
2010-02-24 04:27:55
+2
A:
I have struggled with this. Spark with iText was easy to use, but the PDF formatting was limited. I would love to see your sample where you are using a template PDF file, changing content and then writing to a stream.
found 2 resouces that might helped me:http://www.codeproject.com/KB/aspnet/PdfReportingDemo.aspxandhttp://www.c-sharpcorner.com/uploadfile/scottlysle/pdfgenerator_cs06162007023347am/pdfgenerator_cs.aspx
Dai Bok
2010-08-20 12:49:43