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

C#将html转pdf

2016-04-01 09:51 459 查看
publicstringHtmlToPdf(stringurl)
{
boolsuccess=true;
//stringdwbh=url.Split('?')[1].Split('=')[1];
//CommonBllHelper.CreateUserDir(dwbh);
//url=Request.Url.Host+"/html/"+url;
stringguid=DateTime.Now.ToString("yyyyMMddhhmmss");
stringpdfName="1.pdf";
//stringpath=Server.MapPath("~/kehu/"+dwbh+"/pdf/")+pdfName;
stringpath="D:\\"+pdfName;
try
{
if(string.IsNullOrEmpty(url)||string.IsNullOrEmpty(path))
success=false;
stringstr=Server.MapPath("~\\bin\\wkhtmltopdf.exe");
Processp=System.Diagnostics.Process.Start(str,url+""+path);
p.WaitForExit();
if(!System.IO.File.Exists(str))
success=false;
if(System.IO.File.Exists(path))
{
FileStreamfs=newFileStream(path,FileMode.Open);
byte[]bytes=newbyte[(int)fs.Length];
fs.Read(bytes,0,bytes.Length);
fs.Close();
if(Request.UserAgent!=null)
{
stringuserAgent=Request.UserAgent.ToUpper();
if(userAgent.IndexOf("FIREFOX",StringComparison.Ordinal)<=0)
{
Response.AddHeader("Content-Disposition",
"attachment;filename="+HttpUtility.UrlEncode(pdfName,Encoding.UTF8));
}
else
{
Response.AddHeader("Content-Disposition","attachment;filename="+pdfName);
}
}
Response.ContentEncoding=Encoding.UTF8;
Response.ContentType="application/octet-stream";
//通知浏览器下载文件而不是打开
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
fs.Close();
System.IO.File.Delete(path);
}
else
{
Response.Write("文件未找到,可能已经被删除");
Response.Flush();
Response.End();
}
}
catch(Exceptionex)
{
success=false;
}
return"";
}




protectedvoidPage_Load(objectsender,EventArgse)
{
HtmlToPdf("http://www.deriva.cn");
}


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