ASP.NET MVC 拓展ActionResult实现Html To Pdf 导出
之前实现了html直接转换为word文档的功能,那么是否也同样可以直接转换为pdf文档呢,网上搜了下html to pdf 的开源插件有很多 如:wkhtmltopdf,pdfsharp,itextsharp等
本文使用itextsharp实现如何将html文件转换为pdf文档
首先使用Nuget安装itextsharp插件
- Install-Package itextsharp.xmlworker
创建FileContentResult文件继承自ActionResult,方法HtmlToPdf中实现了如何将一段html转换为pdf文档逻辑,itextsharp.xmlworker能够支持丰富的css和html标签,但是有一个很大的缺点就是不支持中文,网上的一些解决中文字体的逻辑,在新版里面已经不支持了,在以下的示例代码中已经解决此问题,重点是以下两部代码:
FontFactory.RegisterDirectories();//注册当前系统中所支持的字体
worker.ParseXHtml(pdfWriter, document, new MemoryStream(Encoding.UTF8.GetBytes(sbHtml.ToString())), null, Encoding.UTF8, new UnicodeFontFactory()); //指定要使用的字体
- public
class PdfContentResult : ActionResult - {
- public PdfContentResult() : this(null, null) { }
- public PdfContentResult(string viewName) : this(null, viewName) { }
- public PdfContentResult(object model) : this(model, null) { }
- public PdfContentResult(object model, string viewName)
- {
- this.ViewName = viewName;
- ViewData = null != model ? new ViewDataDictionary(model) : null;
- }
- public ViewDataDictionary ViewData { get; set; } = new ViewDataDictionary();
- public
string ViewName { get; set; } - public IView View { get; set; }
- public
override
void ExecuteResult(ControllerContext context) - {
- if (String.IsNullOrEmpty(ViewName))
- {
- ViewName = context.RouteData.GetRequiredString("action");
- }
- if (ViewData == null)
- {
- ViewData = context.Controller.ViewData;
- }
- ViewEngineResult result = ViewEngines.Engines.FindView(context, ViewName, null);
- View = result.View;
- StringBuilder sbHtml = new StringBuilder();
- TextWriter txtWriter = new StringWriter(sbHtml);
- ViewContext viewContext = new ViewContext(context, View, ViewData, context.Controller.TempData, txtWriter);
- result.View.Render(viewContext, txtWriter);
- HttpResponseBase httpResponse = context.HttpContext.Response;
- httpResponse.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
- //加入此头部文件会直接下载pdf文件,而不是在浏览器中预览呈现
- //context.HttpContext.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf", ViewName));
- HtmlToPdf(sbHtml, httpResponse);
- result.ViewEngine.ReleaseView(context, View);
- }
- private
static
void HtmlToPdf(StringBuilder sbHtml, HttpResponseBase httpResponse) - {
- using (Document document = new Document(PageSize.A4, 4, 4, 4, 4))
- {
- using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, httpResponse.OutputStream))
- {
- document.Open();
- FontFactory.RegisterDirectories();//注册系统中所支持的字体
- XMLWorkerHelper worker = XMLWorkerHelper.GetInstance();
- //UnicodeFontFactory 自定义实现解决itextsharp.xmlworker 不支持中文的问题
- worker.ParseXHtml(pdfWriter, document, new MemoryStream(Encoding.UTF8.GetBytes(sbHtml.ToString())), null, Encoding.UTF8, new UnicodeFontFactory());
- document.Close();
- }
- }
- }
- }
UnicodeFontFactory完整代码
- public
class UnicodeFontFactory : FontFactoryImp - {
- static UnicodeFontFactory()
- {
- }
- public
override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached) - {
- return FontFactory.GetFont("arial unicode ms", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- }
- }
如何确定哪些字体在itextsharp中是支持中文的呢,可以通过下面这个小程序验证输出所有的字体名称,及是否支持中文
通过控制台应用程序执行完成后,打开生成的pdf文件,查看 字体名称是否有中文 " 我支持中文" ,如果存在则表示支持中文,否则不支持中文
- Document document = new Document();
- PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"c:\pdf\pdf.pdf", FileMode.Create));
- document.Open();
- FontFactory.RegisterDirectories();
- foreach (var item in FontFactory.RegisteredFonts)
- {
- Font font = FontFactory.GetFont(item, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- document.Add(new Paragraph(item + "<p>我支持中文</p>", font));
- }
- document.Close();
上面说了如何转换html为pdf及怎么解决中文字体的问题,那么怎么使用定义的PdfContentResult呢,
使用方式一:直接在控制器的Action方法中返回PdfContentResult实例
- public
class PdfController : Controller - {
- // GET: Pdf
- public ActionResult Index()
- {
- return
new PdfContentResult(null,"index"); - }
- }
使用方式二:添加Controller类的拓展方法,然后在控制器的Action方法中返回对应的拓展方法
- public
static
class ControllerExtensions - {
- public
static PdfContentResult Pdf(this Controller controller, object model) - {
- return
new PdfContentResult(model); - }
- public
static PdfContentResult Pdf(this Controller controller, object model, string fileName) - {
- return
new PdfContentResult(model, fileName); - }
- public
static PdfContentResult Pdf(this Controller controller, string fileName) - {
- return
new PdfContentResult(fileName); - }
- }
这种感觉用起来是不是与return view();一样
- public
class PdfController : Controller - {
- // GET: Pdf
- public ActionResult Index()
- {
- return
this.Pdf(null, "index"); - }
- }
可能有人会问pdf文档的内容在哪里维护,直接打开Action对应的View视图,像写mvc页面一样布局pdf内容就可以了
至于itextsharp更多功能支持,请参考此文档:http://developers.itextpdf.com/
ASP.NET MVC 拓展ActionResult实现Html To Pdf 导出的更多相关文章
- Asp.net MVC Razor视图模版动态渲染PDF,Razor模版生成静态Html
Asp.net MVC Razor视图模版动态渲染PDF,Razor模版生成静态Html 1.前言 上一篇文章我开源了轮子,Asp.net Core 3.1 Razor视图模版动态渲染PDF,然后,很 ...
- [转载]深入理解ASP.NET MVC之ActionResult
Action全局观 在上一篇最后,我们进行到了Action调用的“门口”: 1 if (!ActionInvoker.InvokeAction(ControllerContext, actionNam ...
- Asp.net MVC 之 ActionResult
Action运行完后,回传的值通过ActionResult 类别或者其衍生的类别操作.ActionResult是一个抽象类,因此,Asp.net MVC 本身就实作了许多不同类型的ActionResu ...
- asp.net mvc之ActionResult
Web服务器接收到一个客户端请求以后,会对请求予以相应,而这个响应是通过Response来控制的, 但是在asp.net mvc 里,这部分的工作是由ActionResult来完成的, ActionR ...
- ASP.NET MVC自定义ActionResult实现文件压缩
有时候需要将单个或多个文件进行压缩打包后在进行下载,这里我自定义了一个ActionResult,方便进行文件下载 using System; using System.Collections; usi ...
- ASP.NET MVC 拓展ViewResult实现word文档下载
最近项目中有同事用到word文档导出功能,遇到了一些导出失败问题,帮其看了下解决问题的同事,看了下之前的代码发现几个问题: 代码编写不规范,word导出功能未收口 重复代码导出都是 实现逻辑比较复 ...
- ASP.NET MVC 中 ActionResult 和 ViewResult 在使用上的区别
如果确认你返回的是一个视图(view),你可以直接返回类型为ViewResult. 如果你并不是很清楚,或者你根本不想去理解这些东西,你可以直接返回ActionResult
- Asp.net MVC 控制器ActionResult的例子
ActionResult 父类型 ViewResult View() 多重载应用 PartialViewResult PartialView() 部分试图 New EmptyResult() 空 如 ...
- Asp.net MVC 之ActionResult
ActionResult 派生出以下子类: ViewResult 返回一个网页视图 PartialViewResult 返回一个网页视图,但不适用布局页. ContentResult 返回一段字符串文 ...
随机推荐
- 再探OAuth2
原文: http://www.cnblogs.com/Irving/p/4134629.html web:http://oauth.net/2/ rfc: http://tools.ietf.org/ ...
- objective-c NSMutableAttributedString
NSMutableAttributedString 是一个很强悍的富文本处理字符串,可以方便的实现一个字符串中某个字符的样式处理.我把我下面代码实现的功能步骤说一下:首先拼接两个字符串,然后给前前半部 ...
- 市面上常见的javaEE WEB服务软件
常见的市面上web服务软件 Tomcat:轻量级的WEB应用程序服务器(开源),开源组织Apache的产品.免费的.支持部分的JavaEE规范.(servlet.jsp.jdbc,但ejb, rmi不 ...
- Verilog学习笔记认识提升篇(一)...............时序的基本概念(待补充)
建立和保持时间: 建立时间(Tsu)是指在时钟上升沿到来之前数据必须保持稳定的时间,保持时间(Th)是指在时钟上升沿到来以后数据必须保持稳定的时间.一个数据需要在时钟的上升沿被锁存,那么这个数据就必须 ...
- 抽取的BaseFragment和LoadingPage
[BaseFragment]: public abstract class BaseFragment extends Fragment { /*★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ...
- 「Ionic」使用chrom時的跨域問題
前言:在angularjs請求數據時,會遇到跨域問題,解決辦法有很多,但是都不是我想要的(很多人云亦云,都解決不了問題).如果你只是想在本機測試使用,可以參考如下設置. 具體辦法: 1.在电脑上新 ...
- Linux文件查看/编辑方法介绍
转载:https://www.centos.bz/2011/10/linux-file-view-edit/ cat 命令介绍 cat 命令的原含义为连接(concatenate), 用于连接多个文件 ...
- C#如何在DataGridViewCell中自定义脚本编辑器
上一篇博文探讨了如何自定义DataGridViewColumn实现一个TreeViewColumn来在DataGridView控件中显示TreeView控件,其实我们还可以继续发挥想象,自定义其他的列 ...
- jQuery 特效:盒子破碎和移动动画效果
今天,我们将创建一个使用 jQuery 制作的非常甜蜜的动画效果.我们的想法是在网站的顶部有小盒子,当一个菜单项被点击时,箱子动画形成的主要内容区域分散在各处.我们会用一些不同的动画效果,我们将为菜单 ...
- MixItUp:超炫!基于 CSS3 & jQuery 的过滤和排序插件
MixItUp 是一款轻量,但功能强大的 jQuery 插件,提供了对分类和有序内容的美丽的动画过滤和排序功能.特别适合用于作品集网站,画廊,图片博客以及任何的分类或有序内容. 它是如何工作的? Mi ...