我想在控制器上调用一个动作。让控制器从模型中获取数据。然后运行该视图并生成PDF。我发现的唯一示例是在Lou的一篇文章中http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action。他的代码非常优雅。该视图正在使用ITextSharp生成PDF。唯一的缺点是他的示例使用了Spark View Engine。有没有办法使用标准的Microsoft视图引擎来做类似的事情?
我想在控制器上调用一个动作。让控制器从模型中获取数据。然后运行该视图并生成PDF。我发现的唯一示例是在Lou的一篇文章中http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action。他的代码非常优雅。该视图正在使用ITextSharp生成PDF。唯一的缺点是他的示例使用了Spark View Engine。有没有办法使用标准的Microsoft视图引擎来做类似的事情?
Answers:
我使用iTextSharp在MVC中生成动态PDF。您需要做的就是将PDF放入Stream对象,然后ActionResult返回一个FileStreamResult。我还设置了内容配置,以便用户可以下载它。
公共FileStreamResult PDFGenerator()
{
    流fileStream = GeneratePDF();
    HttpContext.Response.AddHeader(“ content-disposition”, 
    “附件;文件名= form.pdf”);
    返回新的FileStreamResult(fileStream,“ application / pdf”);
}
我也有代码,使我能够提取模板PDF,向其中写入文本和图像等(如果您想这样做)。
私人Stream GeneratePDF()
{
    //创建您的pdf并将其放入流中... pdf变量如下
    //来自我用来将内容写入PDF文件的类
    MemoryStream ms =新的MemoryStream();
    byte [] byteInfo = pdf.Output();
    ms.Write(byteInfo,0,byteInfo.Length);
    ms.Position = 0;
    返回ms;
}
    我们对该问题的最终答案是使用Rotativa。
它像其他解决方案一样包装了WKhtmltopdf.exe,但这是我发现的最简单的使用方法
我继续投票,其他所有也能很好解决问题的答案,但这就是我们用来解决上面问题中所提出问题的方式。它与其他答案不同。
这是Rotativa教程。
安装后,这就是您所需要的
public ActionResult PrintInvoice(int invoiceId)
{
  return new ActionAsPdf(
                 "Invoice", 
                 new { invoiceId= invoiceId }) 
                 { FileName = "Invoice.pdf" };
}
非常非常简单。
用html创建布局并随后打印为pdf是最快的方法。
html到pdf的转换是由phantomjs,wkhtmltopdf或jsreport提供的
jsreport提供与asp.net mvc视图的直接集成,您可以在其中仅用属性标记控制器动作,它将为您打印pdf而不是html。
免责声明:我是jsreport的作者
这是一个古老的问题,但仍然是一个相关的问题,我想我只想分享一下我已经实施的效果很好的问题。
安装NuGet包TuesPechkin-Pechkin库中的一个基于WkHtmlToPdf的派生,该派生使用Webkit引擎将HTML页面转换为PDF。
编写一个小助手来读取视图并将其转换为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() { }
}
上面的艰苦工作来自这里:http : //wouterdekort.blogspot.co.uk/2012/10/rendering-aspnet-mvc-view-to-string-in.html?showComment=1414603363455#c7863520150405064571
创建一个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");
}
TuesPechkin从nuget下载后,请不要忘记下载,TuesPechkin.Wkhtmltox.Win32否则TuesPechkin.Wkhtmltox.Win64下载时将不包含该内容。
                    我也遇到了这个http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3。它既简单又迅速,并且非常适合MVC。
但是,到目前为止,唯一的缺点是您想要的布局不太灵活,例如,您对表格和通过html的单元格边框没有太多控制。某种支持可以强制打开新页面,但是您必须对iTextsharp应用补丁。
回复很晚,但是我发现以下URL可以帮助我快速获得结果:
(确保您通过使用Nuget包来引用iTextSharp DLL)
编辑 这是我用来使表格看起来有些不同的代码(这也是横向的:
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");
            }
        }
希望这对其他人也有帮助。
一个在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);
        }
您可以在此链接上查看详细说明。拜访这里。
Curtesoy:thelearninguy.com