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 返回一段字符串文 ...
随机推荐
- serialize()序列化
- 使用List把一个长字符串分解成若干个短字符串
把一个长字符串分解成若干个固定长度的短字符串,由于事先不知道长字符串的长度,以及短字符串的数量,只能使用List. public static void get_list_sbody(String s ...
- Hack语言特性之类型化
Hack最基础的特性就是类型标注.PHP5已经开始支持对象的类型化,PHP7也提供了标量类型化声明.Hack提供了全面的类型标注支持,与其typecher配合使用,还可以实现快速.前置静态类型验证. ...
- 算法:二分查找(python版)
#!/usr/bin/env python #coding -*- utf:8 -*- #二分查找#时间复杂度O(logn)#一个时间常量O(1)将问题的规模缩小一半,则O(logn) import ...
- 2015暑假多校联合---Assignment(优先队列)
原题链接 Problem Description Tom owns a company and he is the boss. There are n staffs which are numbere ...
- Scalaz(50)- scalaz-stream: 安全的无穷运算-running infinite stream freely
scalaz-stream支持无穷数据流(infinite stream),这本身是它强大的功能之一,试想有多少系统需要通过无穷运算才能得以实现.这是因为外界的输入是不可预料的,对于系统本身就是无穷的 ...
- [javaSE] 反射-方法的反射
1.如何获取某个方法 方法的名称和方法的参数列表才能唯一决定一个方法 2.方法反射的操作 method.invoke(); package com.tsh.reflect; import java.l ...
- 信鸽推送.NET SDK 开源
github 地址 https://github.com/yeanzhi/XinGePushSDK.NET 传送门如何安装 建议使用nuget安装包,搜索"信鸽"即可 ...
- GJM : Taurus.MVC 2.0 开源发布:WebAPI开发教程 [转载]
Taurus.MVC 2.0 开源发布:WebAPI开发教程 转载自http://www.cnblogs.com/cyq1162/p/6069020.html 因是新手 粘贴时有一个版权问题 本文原 ...
- Git安装图解
msysgit是Windows版的Git,提供了命令行操作 下载地址:http://msysgit.github.io/