Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC how to get view to generate PDF

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?

like image 372
Eric Brown - Cal Avatar asked Apr 22 '09 21:04

Eric Brown - Cal


People also ask

How do I create an automatic PDF?

In Windows 10, click the Printer dropdown menu, then select the Save as PDF option. This is a virtual printer of sorts, and it makes a PDF file. Choose how to format your document, as shown above, then click Save, and Windows will ask where you want to save the PDF file.


2 Answers

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; } 
like image 101
David Avatar answered Oct 10 '22 19:10

David


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.

like image 22
Eric Brown - Cal Avatar answered Oct 10 '22 19:10

Eric Brown - Cal