Fork me on GitHub

HTML生成PDF(c#)

Calling wkhtmltopdf to generate PDF from HTML 老外最多人加分的那篇做法,使用wkhtmtopdf(GPL协议)可以省很多程序代码, 首先到官网http://code.google.com/p/wkhtmltopdf/downloads/list
找installer.exe下载

wkhtmltopdf,一个集成好了的exe文件(C++编写),基本的调用方法是, wkhtmltopdf.exe http://passport.yupsky.com/ac
count/register e:\yupskyreg.pdf

,可以先在命令行测试一下,有其他的需要可以在命令行通过wkhtmltopdf --help查询,如果是超长页的花,可以用命令

wkhtmltopdf.exe http://passport.yupsky.com/ac
count/register e:\yupskyreg.pdf  -H --outline (-H是添加默认标题,--outline是添加pdf的左侧概要哦!)而且可以批量生成哦,中间用空格隔开image

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/*要引用以下命名空间*/
using System.Diagnostics;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

//Button的Click事件(把Url的网页内容转成PDF)
    protected void btn_execute_Click(object sender, EventArgs e)
    {

        //因为Web 是多线程环境,避免甲产生的文件被乙下载去,所以档名都用唯一
        string fileNameWithOutExtention = Guid.NewGuid().ToString();

        //执行wkhtmltopdf.exe
        Process p = System.Diagnostics.Process.Start(@"D:\wkhtmltopdf\wkhtmltopdf.exe", @"http://msdn.microsoft.com/zh-cn D:\" + fileNameWithOutExtention + ".pdf");

        //若不加这一行,程序就会马上执行下一句而抓不到文件发生意外:System.IO.FileNotFoundException: 找不到文件 ''。
        p.WaitForExit();


        //把文件读进文件流
        FileStream fs = new FileStream(@"D:\" + fileNameWithOutExtention + ".pdf", FileMode.Open);
        byte[] file = new byte[fs.Length];
        fs.Read(file, 0, file.Length);
        fs.Close();

        //Response给客户端下载
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=" + fileNameWithOutExtention + ".pdf");//强制下载
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(file);


    }
}

在GitHub上发现2个相关的项目,其中Pechkin这个项目不需要单独安装wkhtmltopdf ,就是.NET的库了。

C# wrapper around excellent wkhtmltopdf console utility  https://github.com/codaxy/wkhtmltopdf

.NET Wrapper for WkHtmlToPdf static DLL. Allows you to utilize full power of the libra:https://github.com/gmanny/Pechkin

posted @ 2012-09-07 22:42  张善友  阅读(26724)  评论(9编辑  收藏  举报