关于HTML生成PDF文件
原文:http://blog.csdn.net/nlx0201/archive/2010/09/15/5885711.aspx
又是引用第三方DLL的一篇方法,后来建议作者用Reflector反编译提出方法了。
之前看过一些通过C#代码生成PDF文件的方式,用得最多的IText可以实现HTML页面生成PDF文件(也有一些人在机器上装了PDF打印机,使用打印来生成PDF),不过我个人觉得IText生成PDF的方法比较复杂,而在相当一段时间内查看资料后,发现有另外一个插件可以更好的控制HTML生成PDF文件。具体方法介绍如下:
首先,下载一个ABCpdf .NET 7.0,下载地址:http://www.oyksoft.com/soft/8576.html,然后安装。此外安装的时候需要注册一下。
其次,在安装目录下找到ABCpdf.dll文件,通过VS2008添加这个类库。
最后,就是在项目中使用了,如下:
一,在当前需要生成PDF文件的页面放一个按钮。按钮的 方法如下:

protected void lbPdf_Click(object sender, EventArgs e)
{
string name = Request.QueryString["name"];
Response.Redirect("Print.ashx?url=" + Request.Url.ToString() + "&name=" + name+"&group="+group);
}
{
string name = Request.QueryString["name"];
Response.Redirect("Print.ashx?url=" + Request.Url.ToString() + "&name=" + name+"&group="+group);
}
二,新建一个print.ashx页,下面就是这个页面的代码:

<%@ WebHandler Language="C#" Class="print" %>
using System;
using System.Web;
using WebSupergoo.ABCpdf7;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Text;
public class print : IHttpHandler {
public void ProcessRequest (HttpContext context) {
if (!string.IsNullOrEmpty(context.Request.QueryString["url"]) && !string.IsNullOrEmpty(context.Request.QueryString["name"]))
{
string url = context.Request.QueryString["url"];
getPdf(url, context.Request.QueryString["name"],context.Request.QueryString["group"]);
}
}
public bool IsReusable {
get {
return false;
}
}
public void getPdf(string pdf, string name,string group)
{
Random r = new Random();
Doc theDoc = new Doc();
theDoc.TopDown = true;
theDoc.Rect.String = "22 15 820 580";//控制显示的大小205 300 632 895
theDoc.MediaBox.String = "0 0 842 595";//控制页面的大小
string reg = @"\<a id\=(.)+\</a\>";//这段正则主要是去掉页面中自己不需要显示的东西
string reg1 = @"body\{(.)+\}";
string temp=Regex.Replace(Regex.Replace(getHtml(pdf),reg1,""),reg,"");
temp = temp.Replace("{$name$}", name.Split(',')[0]).Replace("{$group$}", group);
int theID = theDoc.AddImageHtml(temp, true, 0, false);
while (true)
{
if (!theDoc.Chainable(theID))
{
break;
}
theDoc.Page = theDoc.AddPage();
theID = theDoc.AddImageToChain(theID);
}
byte[] theData = theDoc.GetData();
FileCreate(name, theData);
if (File.Exists(HttpContext.Current.Server.MapPath(name + ".pdf")))
{
HttpContext.Current.Response.Write(string.Format("<a target='_blank' href='{0}'>下载</a>", name + ".pdf"));
}
}
//创建文件
public static void FileCreate(string name, byte[] datas)
{
FileInfo CreateFile = new FileInfo(HttpContext.Current.Server.MapPath(name + ".pdf")); //创建文件
if (CreateFile.Exists)
{
CreateFile.Delete();
}
FileStream FS = CreateFile.Create();
FS.Write(datas, 0, datas.Length);
FS.Close();
}
private string getHtml(string Url)
{
string strResult = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8);
strResult = streamReader.ReadToEnd();
}
catch
{
}
return strResult;
}
}
using System;
using System.Web;
using WebSupergoo.ABCpdf7;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Text;
public class print : IHttpHandler {
public void ProcessRequest (HttpContext context) {
if (!string.IsNullOrEmpty(context.Request.QueryString["url"]) && !string.IsNullOrEmpty(context.Request.QueryString["name"]))
{
string url = context.Request.QueryString["url"];
getPdf(url, context.Request.QueryString["name"],context.Request.QueryString["group"]);
}
}
public bool IsReusable {
get {
return false;
}
}
public void getPdf(string pdf, string name,string group)
{
Random r = new Random();
Doc theDoc = new Doc();
theDoc.TopDown = true;
theDoc.Rect.String = "22 15 820 580";//控制显示的大小205 300 632 895
theDoc.MediaBox.String = "0 0 842 595";//控制页面的大小
string reg = @"\<a id\=(.)+\</a\>";//这段正则主要是去掉页面中自己不需要显示的东西
string reg1 = @"body\{(.)+\}";
string temp=Regex.Replace(Regex.Replace(getHtml(pdf),reg1,""),reg,"");
temp = temp.Replace("{$name$}", name.Split(',')[0]).Replace("{$group$}", group);
int theID = theDoc.AddImageHtml(temp, true, 0, false);
while (true)
{
if (!theDoc.Chainable(theID))
{
break;
}
theDoc.Page = theDoc.AddPage();
theID = theDoc.AddImageToChain(theID);
}
byte[] theData = theDoc.GetData();
FileCreate(name, theData);
if (File.Exists(HttpContext.Current.Server.MapPath(name + ".pdf")))
{
HttpContext.Current.Response.Write(string.Format("<a target='_blank' href='{0}'>下载</a>", name + ".pdf"));
}
}
//创建文件
public static void FileCreate(string name, byte[] datas)
{
FileInfo CreateFile = new FileInfo(HttpContext.Current.Server.MapPath(name + ".pdf")); //创建文件
if (CreateFile.Exists)
{
CreateFile.Delete();
}
FileStream FS = CreateFile.Create();
FS.Write(datas, 0, datas.Length);
FS.Close();
}
private string getHtml(string Url)
{
string strResult = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8);
strResult = streamReader.ReadToEnd();
}
catch
{
}
return strResult;
}
}
我在整个项目中生成PDF文件都是使用这个方法,我个人觉得这个方法很简单。我也经常在论坛里面看到不少的人都在询问HTML页面直接生成PDF文件的问题,所以今天就共享下我的做法
分类:
Web志
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
2009-12-07 ASP.NET MVC Membership 权限 漫谈
2009-12-07 C# override,new 的区别+C# 接口的显示实现和隐示实现
2009-12-07 .NET URL 301转向方法的实现
2009-12-07 【转】解决大量图片造成的页面延迟
2009-12-07 【转载】正则表达式 地址匹配(地区城市地址)