Asp.Net MVC如何获取视图生成PDF [英] Asp.Net MVC how to get view to generate PDF

查看:416
本文介绍了Asp.Net MVC如何获取视图生成PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个控制器上的操作。有控制器从模型中获取数据。该视图然后运行,并生成一个PDF文件。我发现的唯一的例子是娄<一的一篇文章中href=\"http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action\">http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action.他的code是非常优雅。该视图使用iTextSharp的生成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?

推荐答案

我用iTextSharp的生成在MVC动态PDF文件。所有你需要做的就是把你的PDF到一个流对象,然后你的ActionResult返回FileStreamResult。我还设置了内容部署,以便用户可以下载它。

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

我也有code,让我带一个模板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).


  • 注:必须将流位置设置为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;
}

这篇关于Asp.Net MVC如何获取视图生成PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆