前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HTML生成PDF(c#)

HTML生成PDF(c#)

作者头像
张善友
发布2018-01-29 16:53:01
1.8K0
发布2018-01-29 16:53:01
举报
文章被收录于专栏:张善友的专栏张善友的专栏

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
image
代码语言:js
复制
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-09-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档