您的位置:首页 > Web前端 > HTML

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

2014-02-09 11:51 399 查看
代码篇

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

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

页面截图如:





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

1.步骤

首先新建一个项目HTMLtoPDFOutPutStream

新建目录output;作为临时输出目录

新建resoure目录,用于保存wkhtmltopdf.exe等各个组件

接着添加一个WebForm1.aspx,在页面上添加一个按钮

最后在按钮的点击事件上写代码

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

stringfileName=Guid.NewGuid().ToString();

[code]stringoutputPath=Server.MapPath("output");
stringsavepath=string.Format(outputPath+"\\"+fileName+".pdf");//最终保存


stringurl="http://www.cnblogs.com/ITGirl00/";


try

{

if(!string.IsNullOrEmpty(url)||!string.IsNullOrEmpty(savepath))

{

Processp=newProcess();

stringresource=HttpContext.Current.Server.MapPath("resoure");

stringdllstr=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

{

FileStreamfs=newFileStream(savepath,FileMode.Open);

byte[]file=newbyte[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(Exceptionee)

{


thrownewException(ee.ToString());

}



}

}



}

catch(Exceptionex)

{

thrownewException(ex.ToString());

}

[/code]


3.效果图




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

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

Technorati标签:wkhtmtopdf,HTMLTOPDF,HTML转换PDF,outputStream
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: