Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...