我使用HTML开发使用asp.net mvc4的报告,我想用asp.net MVC4将此报告导出为PDF文件,有人帮帮我吗?谢谢!
答案 0 :(得分:6)
使用Razor PDF生成PDF报告。这是一个简单的过程。
第1步 - 创建MVC应用程序
第2步 - 安装Rotativa PDF Nuget。
第3步 - 放置一个这样的简单模型
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
步骤4 - 为我们上面创建的模型创建一个简单视图,将视图命名为Index。
@model IEnumerable<WebApplication1.Controllers.Person>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
}
</table>
步骤5 - 创建一个简单的控制器动作。
public ActionResult IndexNew() { return new ActionAsPdf("GeneratePDF"); } public ActionResult GeneratePDF() { List<Person> persons = new List<Person>(); persons.Add(new Person() { Age = "29", Name = "Rami1" }); persons.Add(new Person() { Age = "28", Name = "Rami2" }); return View("Index", persons); }
运行应用程序并导航到IndexNew Controller Action,将从GeneratePDF()Action生成PDF,并将由浏览器下载,如下所示 -
答案 1 :(得分:4)
看看这个应用程序:
http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC
如果您想直接下载文件,可以使用FileContentResult:
protected FileContentResult ViewPdf(string pageTitle, string viewName, object model)
{
string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model);
byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle);
return File(buffer, "application/pdf","file.pdf");
}
答案 2 :(得分:0)
如果报告是同一应用程序中的另一个视图,您可以使用以下C#获取该视图的HTML字符串,然后将HTML字符串转换为PDF以在缓冲区中生成PDF,该缓冲区可以保存在服务器上或发送到浏览器下载。代码使用evo html to pdf converter for .net将HTML字符串转换为PDF。此方法的优点是会话数据在转换期间在报表视图中可用:
[HttpPost]
public ActionResult ConvertPageInSameSessionToPdf(FormCollection collection)
{
object model = null;
ViewDataDictionary viewData = new ViewDataDictionary(model);
// The string writer where to render the HTML code of the view
StringWriter stringWriter = new StringWriter();
// Render the Index view in a HTML string
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Report_View", null);
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
viewData,
new TempDataDictionary(),
stringWriter
);
viewResult.View.Render(viewContext, stringWriter);
// Get the view HTML string
string htmlToConvert = stringWriter.ToString();
// Get the base URL
String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Report_View".Length);
// Convert the HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "Report.pdf";
return fileResult;
}