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

王朝学院·作者佚名  2016-05-21
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

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

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

页面截图如:

目标:我们需要做出上面这个效果的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.效果图===小小提示===(1)使用wkhtmltopdf时,PDF保存的文件夹不能有非Ansi字符,如中文、日文等,且转换gb2312、韩文charset、日文charset等非utf-8\ansi等网页时,会出现乱码

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

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航