Asp.Net MVC如何获取生成PDF的视图

时间:2009-04-22 21:59:43

标签: asp.net-mvc pdf

我想在控制器上调用一个动作。让控制器从模型中获取数据。然后该视图将运行并生成PDF。我发现的唯一例子是Lou http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action的一篇文章。他的代码非常优雅。该视图使用ITextSharp生成PDF。唯一的缺点是他的例子使用了Spark View引擎。有没有办法用标准的Microsoft视图引擎做类似的事情?

8 个答案:

答案 0 :(得分:82)

我使用iTextSharp在MVC中生成动态PDF。您需要做的就是将PDF放入Stream对象,然后ActionResult返回FileStreamResult。我还设置了内容处理,以便用户可以下载它。

public FileStreamResult PDFGenerator()
{
    Stream fileStream = GeneratePDF();

    HttpContext.Response.AddHeader("content-disposition", 
    "attachment; filename=form.pdf");

    return new FileStreamResult(fileStream, "application/pdf");
}

我还有代码,可以让我获取PDF模板,写文本和图像等(如果你想这样做)。

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

答案 1 :(得分:23)

我们对此问题的最终答案是使用Rotativa

它像其他一些解决方案一样包装WKhtmltopdf.exe,但它是迄今为止我发现的最容易使用的

我上去投了所有其他答案,这也很好地解决了问题,但这就是我们用来解决上述问题中提出的问题。它与其他答案不同。

这是Rotativa Tutorial

安装后,这就是您的需要

public ActionResult PrintInvoice(int invoiceId)
{
  return new ActionAsPdf(
                 "Invoice", 
                 new { invoiceId= invoiceId }) 
                 { FileName = "Invoice.pdf" };
}

非常简单。

答案 2 :(得分:6)

在html中创建布局并在之后打印成pdf是最快的方法。

html into pdf转换由phantomjswkhtmltopdfjsreport

提供

jsreport提供与asp.net mvc视图的直接集成, 你可以用属性标记控制器动作,它会为你打印pdf而不是html。

有关此blog post

的更多信息

免责声明:我是jsreport的作者

答案 3 :(得分:6)

这是一个老问题,但仍然具有相关性,我认为我只是分享我已经实施的那些效果很好。

  1. 安装NuGet包TuesPechkin - 基于WkHtmlToPdf的Pechkin库中的一个fork,它使用Webkit引擎将HTML页面转换为PDF。

  2. 编写一个小助手来读取视图并将其转换为HTML字符串(mvcContext是this.HttpContext)。当然,替换是可选的!:

    public static string RenderViewToString(HttpContextBase mvcContext, string area, string controllerName, string viewName, object model)
    {
        var context = System.Web.HttpContext.Current;
        var contextBase = mvcContext;
        var routeData = new RouteData();
        if (area == null) area = "";
    
        routeData.DataTokens.Add("area", area);
    
        routeData.Values.Add("controller", controllerName);
    
        var controllerContext = new ControllerContext(contextBase,
                                                routeData,
                                                new EmptyController());
    
        var razorViewEngine = new RazorViewEngine();
        var razorViewResult = razorViewEngine.FindView(controllerContext,
                                                    viewName,
                                                    "",
                                                false);
    
        var writer = new StringWriter();
        var viewContext = new ViewContext(controllerContext,
                                    razorViewResult.View,
                                    new ViewDataDictionary(model),
                                    new TempDataDictionary(),
                                    writer);
        razorViewResult.View.Render(viewContext, writer);
    
        string hostAddress = context.Request.Url.Scheme + "://" + context.Request.Url.Authority;
    
        return writer.ToString()
                     .Replace("src=\"/", "src=\"" + hostAddress + "/")
                     .Replace("<link href=\"/", "<link href=\"" + hostAddress + "/");                         
    }
    
    class EmptyController : ControllerBase
    {
        protected override void ExecuteCore() { }
    }
    
  3. 以上的辛勤工作来自:http://wouterdekort.blogspot.co.uk/2012/10/rendering-aspnet-mvc-view-to-string-in.html?showComment=1414603363455#c7863520150405064571

    1. 创建MVC操作以生成文档

      public ActionResult DownloadPDF(long CentreID)
      {
          var model = GetModel()
      
          IPechkin converter = Factory.Create();
          byte[] result = converter.Convert(Helpers.PDF.RenderViewToString(this.HttpContext, "area", "controller", "action", model);
          MemoryStream outputStream = new MemoryStream();
          outputStream.Write(result, 0, result.Length);
          outputStream.Position = 0;
      
          return File(outputStream, "application/pdf", "filename.pdf");
      }
      

答案 4 :(得分:5)

我也遇到了这个http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3。它简单快捷,适合MVC。

然而,到目前为止唯一的缺点是,你想要有一个不错的布局,它不是很灵活,例如,你没有太多的控制表和通过HTML的单元格边框。它有点支持强制新页面,但你必须在iTextsharp上应用补丁。

答案 5 :(得分:2)

我刚使用wkhtmltopdf,在html中创建布局,然后将其转换为pdf。

简单,可定制,令人敬畏的地狱:)

答案 6 :(得分:0)

非常晚回复,但我发现以下网址帮助我快速得到了我的结果:

(确保您通过使用Nuget包引用iTextSharp DLL)

https://www.aspsnippets.com/Articles/Export-Grid-Html-Table-data-from-database-to-PDF-file-using-iTextSharp-in-ASPNet-MVC.aspx

修改 这是我用来使表格看起来有点不同的代码(这也是景观:

public string GetCssForPdf()
        {
            string css = "";

            css = "th, td" +
                   "{" +
                       "font-family:Arial; font-size:10px" +
                    "}";

            return css;
        }

[HttpPost]
        [ValidateInput(false)]
        public FileResult Export(string GridHtml)
        {
            string webgridstyle = GetCssForPdf();

            string exportData = String.Format("<html><body>{0}{1}</body></html>", "<style>" + webgridstyle + "</style>", GridHtml);
            var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);

            using (var input = new MemoryStream(bytes))
            {
                var output = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
                var writer = PdfWriter.GetInstance(document, output);

                document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                Font headerFont = FontFactory.GetFont("Verdana", 10);
                Font rowfont = FontFactory.GetFont("Verdana", 10);

                writer.CloseStream = false;
                document.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                document.Close();
                output.Position = 0;

                return File(output, "application/pdf", "Pipeline_Report.pdf");

                //return new FileStreamResult(output, "application/pdf");
            }
        }

希望这也有助于其他人。

答案 7 :(得分:0)

在asp.net mvc中使用rotativa软件包的小示例

我们将创建一个函数来填充数据。我们将插入7天(2018年2月1日至2018年2月7日)的数据,其中显示特定日期的第一个拳和最后一个拳,并带有备注。

public ReportViewModel PopulateData()
        {
            var attendances = new List<Attendance>
            {
                new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 01).ToString("ddd"),Date = new DateTime(2018, 02, 01).ToString("d"),FirstPunch = "09:01:00",LastPunch = "06:00:01",Remarks = ""},
                new Attendance{ClassName = "absent",Day = new DateTime(2018, 02, 02).ToString("ddd"),Date = new DateTime(2018, 02, 02).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Absent"},
                new Attendance{ClassName = "holiday",Day = new DateTime(2018, 02, 03).ToString("ddd"),Date = new DateTime(2018, 02, 03).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Democracy Day"},
                new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 04).ToString("ddd"),Date = new DateTime(2018, 02, 04).ToString("d"),FirstPunch = "09:05:00",LastPunch = "06:30:01",Remarks = ""},
                new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 05).ToString("ddd"),Date = new DateTime(2018, 02, 05).ToString("d"),FirstPunch = "09:01:00",LastPunch = "06:00:01",Remarks = ""},
                new Attendance{ClassName = "leave",Day = new DateTime(2018, 02, 06).ToString("ddd"),Date = new DateTime(2018, 02, 06).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Sick Leave"},
                new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 07).ToString("ddd"),Date = new DateTime(2018, 02, 07).ToString("d"),FirstPunch = "08:35:00",LastPunch = "06:15:01",Remarks = ""}
            };


            return new ReportViewModel
            {
                UserInformation = new UserInformation
                {
                    FullName = "Ritesh Man Chitrakar",
                    Department = "Information Science"
                },
                StartDate = new DateTime(2018, 02, 01),
                EndDate = new DateTime(2018, 02, 07),
                AttendanceData = attendances
            };
        }

然后我们将为DownloadPdf创建一个函数。要下载pdf文件,我们需要创建2个函数。 1.下载pdf 2.查看pdf

public ActionResult DownloadPdf()
        {
            var filename = "attendance.pdf";

            /*get the current login cookie*/
            var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k]?.Value);

            return new ActionAsPdf("PdfView", new
            {
                startDate = Convert.ToDateTime(Request["StartDate"]),
                endDate = Convert.ToDateTime(Request["EndDate"])
            })
            {
                FileName = filename,
                /*pass the retrieved cookie inside the cookie option*/
                RotativaOptions = {Cookies = cookies}
            };
        }

public ActionResult PdfView()
        {
            var reportAttendanceData = PopulateData();

            return View(reportAttendanceData);
        }

您可以在此链接上查看详细说明。 访问here

Curtesoy:thelearninguy.com