http://www.simple-talk.com/dotnet/asp.net/asp.net-mvc-action-results-and-pdf-content/

http://www.subvert.ca/Blog/wkhtmltopdf-in-MVC3

http://www.cnblogs.com/ryanding/archive/2010/12/26/1915915.html

http://www.cnblogs.com/shanyou/archive/2012/09/07/2676026.html

Building PDFs dynamically using wkhtmltopdf in a MVC3 application

While working on a recent project, I needed to build a series of PDF documents dynamically, then zip them up into a single file. I checked out a couple of options, including iTextSharp and some non-open-source options. I then decided that I liked the looks of wkhtmltopdf.

In my previous life as a Java developer, I had a similar requirement and used iReport to design and fill a Jasper report with data. I knew that I wanted to stay as far away from that solution as possible. I had to have the ability to quickly make data/style/layout changes and have them all testable, without having to recompile or redeploy anything.

The solution I came up with used Razor views just like any other MVC3 page. So, I was able to preview and debug those views without having to actually generate the PDF, download it, and open it. Once I had the views perfected, I built a few helper classes that would render the view in the background, then use the wkhtmltopdf engine to build my PDF.

wkhtmltopdf introduced a couple of interesting problems, not the least of which is that it uses an executable to generate the PDF. I got around that by putting the executable into my application’s bin directory. This gave me the ability to fire it up in a process, sending in the appropriate parameters, then wait for it to finish and grab the file it created.

I put the following method into a helper class and pass into it an instance of my HttpServerUtilityBase so that I can get the executable’s path, and the url to my view that I had previously developed. It saves the PDF to a temp file, then I read the bytes from it, and promptly delete it.

public byte[] ConvertHtmlToPDF(HttpServerUtilityBase server, string inputUrl){    byte[] bytes = null;

    FileInfo tempFile = new FileInfo(Path.GetTempFileName());

    StringBuilder argument = new StringBuilder();    argument.Append(" --disable-smart-shrinking");    argument.Append(" --no-pdf-compression");    argument.Append(" " + inputUrl);    argument.Append(" " + tempFile.FullName);

    try    {        // to call the exe to convert        using (Process p = new System.Diagnostics.Process())        {            p.StartInfo.UseShellExecute = false;            p.StartInfo.CreateNoWindow = true;            p.StartInfo.FileName = server.MapPath("/bin/wkhtmltopdf.exe");            p.StartInfo.Arguments = argument.ToString();            p.StartInfo.RedirectStandardOutput = true;            p.StartInfo.RedirectStandardError = true;

            p.Start();            p.WaitForExit();        }

        using (FileStream stream = new FileStream(tempFile.FullName, FileMode.Open, FileAccess.Read))        {            bytes = new byte[stream.Length];            stream.Read(bytes, 0, bytes.Length);        }    }    catch (Exception)    {        //logging    }

    tempFile.Delete();    return bytes;}

Depending on your application, once you have the byte array, you can just return that to the client in a FileResult using the appropriate mime-type or drop them into a ZIP file like I did. Hopefully this will help you guys out there that need to produce PDFs in your next MVC3 project.

MVC 导出PDF的更多相关文章

  1. .Net导出pdf文件,C#实现pdf导出

    最近碰见个需求需要实现导出pdf文件,上网查了下代码资料总结了以下代码.可以成功的实现导出pdf文件. 在编码前需要在网上下载个itextsharp.dll,此程序集是必备的.楼主下载的是5.0版本, ...

  2. JS导出PDF插件(支持中文、图片使用路径)

    在WEB上想做一个导出PDF的功能,发现jsPDF比较多人推荐,遗憾的是不支持中文,最后找到pdfmake,很好地解决了此问题.它的效果可以先到http://pdfmake.org/playgroun ...

  3. mvc导出excel 之 新

    前段时间做的mvc导出excel 老大说要进行优化,我原来导出是用npoi插件进行导出,格式是将数据放入到datatable中,然后进行导出. 说要优化的时候就想着将datatable数据导出格式改为 ...

  4. ITextSharp导出PDF表格和图片(C#)

    文章主要介绍使用ITextSharp导出PDF表格和图片的简单操作说明,以下为ITextSharp.dll下载链接 分享链接:http://pan.baidu.com/s/1nuc6glj 密码:3g ...

  5. MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult

    导出EXCEL方法总结 MVC导出数据到EXCEL的方法有很多种,常见的是: 1.采用EXCEL COM组件来动态生成XLS文件并保存到服务器上,然后转到该文件存放路径即可: 优点:可设置丰富的EXC ...

  6. JAVA导出pdf实例

    一.直接导出成PDF   Java代码 1. import java.io.FileNotFoundException; 2. import java.io.FileOutputStream; 3.  ...

  7. 利用ITextSharp导出PDF文件

    最近项目中需要到处PDF文件,最后上网搜索了一下,发现ITextSharp比较好用,所以做了一个例子: public string ExportPDF() { //ITextSharp Usage / ...

  8. iText导出pdf、word、图片

    一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或 ...

  9. Itext导出PDF,word,图片案例

    iText导出pdf.word.图片 一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生 ...

随机推荐

  1. Objective-C 【关于导入类(@class 和 #import的区别)】

    之前我们分析过 #include 和 #import 的区别,#import不会引起交叉编译,#import 确定一个文件只能被导入一次,使在递归包含中不会出现问题. 那么 #import 和 @cl ...

  2. self指向函数地址 动态调用函数的简单例子

    #import <Foundation/Foundation.h> @interface Person : NSObject - (void)test1; - (void)test2:(N ...

  3. docker & nodejs

    Docker 部署 Node js demo程序 1.准备node js程序,使用express框架. mkdir demo 在demo文件夹下建立package.json { "name& ...

  4. Zookeeper-集群环境搭建

    一般为单数台机器,操作系统为linux. zookeeper为java编写,所以必须有java的运行环境. 下载地址:http://mirrors.hust.edu.cn/apache/zookeep ...

  5. UVALive 6811 Irrigation Line(二分图最小点覆盖--匈牙利算法)

    题意:求最少的线可以覆盖一个由0.1两种数字组成的图中所有的1. eg: 只需要两条线即可. 分析: 1.先为上述例子的行列标号 2.若图中数字为1,则代表该数字所在的行与列有关联. 例如第r1行第c ...

  6. Contiki学习入门之概览

    Contiki是专为物联网领域而设计的开源操作系统,适用于联网嵌入式系统和无线传感器网络.由瑞典计算机科学学院的Adam Dunkels团队开发.它有以下几个特点. 1. 网络标准 contiki提供 ...

  7. 使用WebJar管理css、JavaScript文件

    Web前端使用了越来越多的JS或CSS,如jQuery, Backbone.js 和Bootstrap.一般情况下,我们是将这些Web资源拷贝到Java的目录下,通过手工进行管理,这种通方式容易导致文 ...

  8. JSON参数解析工具类

    /// <summary> /// 解析JSON参数 /// </summary> public class JSONParser { JObject jObj = null; ...

  9. Javascript中最常用的55个经典技巧

    Javascript中最常用的55个经典技巧1. oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键<table ...

  10. Linux系统下安装rz/sz命令及使用说明(转载)

    对于经常使用Linux系统的人员来说,少不了将本地的文件上传到服务器或者从服务器上下载文件到本地,rz / sz命令很方便的帮我们实现了这个功能,但是很多Linux系统初始并没有这两个命令.今天,我们 ...