zoukankan      html  css  js  c++  java
  • [转载]HTML生成PDF(c#)

    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

  • 相关阅读:
    macOS 修改键盘重复按键延迟
    stdout 与 stderr 区别
    E. 1-Trees and Queries
    Codeforces Round #615 (Div. 3)
    Codeforces Round 613(div 2)
    Codeforces Edu80
    SPOJ
    快读
    《货车运输》题解--最大生成树&倍增
    倍增思想求lca
  • 原文地址:https://www.cnblogs.com/fx2008/p/2835097.html
Copyright © 2011-2022 走看看