天天看点

wkhtmtopdf--高分辨率HTML转PDF(三)

代码篇

浏览了很多实例,总找不到既能把HTML保存为PDF,同时实现流抛出的,所以自己琢磨了许久,终于实现了这样两个需求的结合体,下面来贡献一下吧~~

下面我们来选择一个网页打印下,保存为PDF,而且实现流抛出保存,假设我们选择“http://www.cnblogs.com/ITGirl00/”

页面截图如:

wkhtmtopdf--高分辨率HTML转PDF(三)

目标:我们需要做出上面这个效果的PDF。

1.步骤

  • 首先新建一个项目HTMLtoPDFOutPutStream
  • 新建目录output;作为临时输出目录
  • 新建resoure目录,用于保存wkhtmltopdf.exe等各个组件
  • 接着添加一个WebForm1.aspx,在页面上添加一个按钮
  • 最后在按钮的点击事件上写代码

2.按钮的点击处理代码:

string fileName = Guid.NewGuid().ToString();      
string outputPath = Server.MapPath("output");      
string savepath = string.Format(outputPath + "\\" + fileName + ".pdf");//最终保存      
string url = "http://www.cnblogs.com/ITGirl00/";      
try      
{      
if (!string.IsNullOrEmpty(url) || !string.IsNullOrEmpty(savepath))      
{      
Process p = new Process();      
string resource = HttpContext.Current.Server.MapPath("resoure");      
string dllstr = string.Format(resource + "\\wkhtmltopdf.exe");      
if (System.IO.File.Exists(dllstr))      
{      
p.StartInfo.FileName = dllstr;      
p.StartInfo.Arguments = " \"" + url + "\"  \"" + savepath + "\"";      
p.StartInfo.UseShellExecute = false;      
p.StartInfo.RedirectStandardInput = true;      
p.StartInfo.RedirectStandardOutput = true;      
p.StartInfo.RedirectStandardError = true;      
p.StartInfo.CreateNoWindow = true;      
p.Start();      
p.WaitForExit();      
try      
{      
FileStream fs = new FileStream(savepath, FileMode.Open);      
byte[] file = new byte[fs.Length];      
fs.Read(file, 0, file.Length);      
fs.Close();      
Response.Clear();      
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");//強制下載      
Response.ContentType = "application/octet-stream";      
Response.BinaryWrite(file);      
}      
catch (Exception ee)      
{      
throw new Exception(ee.ToString());      
}      
}      
}      
}      
catch (Exception ex)      
{      
throw new Exception(ex.ToString());      
}      

3.效果图

wkhtmtopdf--高分辨率HTML转PDF(三)

===小小提示===

(1)使用wkhtmltopdf时,PDF保存的文件夹不能有非Ansi字符,如中文、日文等,且转换gb2312、韩文charset、日文charset等非utf-8\ansi等网页时,会出现乱码

(2)网页上图片无法正确显示是由于图片有链接

Technorati 标签: wkhtmtopdf,HTMLTOPDF,HTML转换PDF,outputStream

作者:

Elaine

出处:http://www.cnblogs.com/ITGirl00/

交流QQ:

392989505