ASP.NET C# MVC使用iTextSharp生成PDF实例_C#从HTML代码生成PDF例子
2014-09-26 10:03:30 By: shinyuu
简介几乎每一个Web应用程序(我已做的项目)都需要一些报告、很多时候、客户要生成的网页
那接下来我就和大家分享一下我在MVC 的项目里面怎么生成 PDF格式的报告
我们要使用iTextSharp、一个免费的C#的PDF库用于创建使用iTextSharp和ASP.NET MVC3报告解决方案
iTextSharp是从Java的PDF库iText的移植一个免费的C#的PDF库、 iText的是在2000年推出
是编程方式创建和操纵的PDF一个流行的开源Java库、与许多成功的开源Java库一样
它被移植到C#的名字叫 iTextSharp、自2008年iTextSharp一直在发展
那么我们是使用HTMLWorker类从iTextSharp来生成一个HTML查看PDF、 HTMLWorker是iTextSharp类
它能够解析HTML文档、并使用所谓iTextSharp的SimpleParser生成PDF、请注意名称SimpleParser
表明并非所有的HTML元素和CSS样式的支持、不过、我可以使用这个解决方案、获得非常不错的效果
有图有真像、先来看看运行效果吧
源代码
我是通过自定义一个 Controller 来实现生成 PDF 功能的
public class PdfViewController : Controller { private readonly HtmlViewRenderer htmlViewRenderer; private readonly StandardPdfRenderer standardPdfRenderer; public PdfViewController() { this.htmlViewRenderer = new HtmlViewRenderer(); this.standardPdfRenderer = new StandardPdfRenderer(); } protected ActionResult ViewPdf(string pageTitle, string viewName, object model) { //Render the view html to a string. string htmlText = this.htmlViewRenderer .RenderViewToString(this, viewName, model); //Let the html be rendered into a PDF //document through iTextSharp. byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle); // Return the PDF as a binary stream to the client. return new BinaryContentResult(buffer, "application/pdf"); } }Controller 的代码、实现上面自定义的Controller
public class HomeController : PdfViewController { public ActionResult Index() { return View(); } public ActionResult PrintCustomers() { CustomerList customerList = CreateCustomerList(); FillImageUrl(customerList, "report.jpg"); return this.ViewPdf("Customer report", "PrintDemo", customerList); } private void FillImageUrl(CustomerList customerList, string imageName) { string url = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")); customerList.ImageUrl = url + "Content/" + imageName; } }View的代码、只有一个Table用于生成PDF
@using MvcReportGeneratorDemo.Models @model CustomerList <br /> <table cellpadding="3" cellspacing="3"> <tr border="1" bgcolor="#777777" color="#ffffff"> <td>Name</td> <td>Address</td> <td>Place</td> </tr> @foreach (Customer customer in Model) { <tr border="1"> <td>@customer.Name</td> <td>@customer.Address</td> <td>@customer.Place</td> </tr> } </table>好了、到这里你的程序就可以生成PDF了、感谢你的访问
最后给大家献上源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1qW8ugHI 密码: hogk
若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力
想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)
或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教
为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛
[email protected] 2016-09-22 18:36:00 3 评 | 回复
博主,这个中文设置,还是没有找到地方,还烦请告知一下。谢谢!