首页 > 代码库 > wkhtmltopdf 生成pdf
wkhtmltopdf 生成pdf
1 public class PdfHelper 2 { 3 4 static string RootPath 5 { 6 get 7 { 8 string AppPath = ""; 9 HttpContext HttpCurrent = HttpContext.Current;10 if (HttpCurrent != null)11 {12 AppPath = HttpCurrent.Server.MapPath("~");13 }14 15 return AppPath.Trim(new char[]{‘\\‘});16 }17 }18 19 20 public static void GetPdf(HttpResponseBase response,string pdfUrl)21 {22 string fileName = Guid.NewGuid().ToString("N") + ".pdf";23 string filePath = RootPath + "\\pdfs\\" + fileName;24 string exePath=RootPath + "\\wkhtmltopdf\\wkhtmltopdf.exe";25 string args=pdfUrl + " --zoom 1.25 \"" + filePath+"\"";26 27 28 Process p =new Process();29 p.StartInfo.FileName = exePath;30 p.StartInfo.Arguments = args;31 p.StartInfo.UseShellExecute = false;32 p.StartInfo.RedirectStandardInput = true;33 p.StartInfo.RedirectStandardOutput = true;34 p.StartInfo.RedirectStandardError = true;35 p.StartInfo.CreateNoWindow = false;36 37 try38 {39 p.Start();40 p.WaitForExit(); 41 p.StandardOutput.ReadToEnd();42 p.Close();43 44 FileStream fs = new FileStream(filePath, FileMode.Open);45 byte[] file = new byte[fs.Length];46 fs.Read(file, 0, file.Length);47 fs.Close();48 49 50 response.Clear();51 response.AddHeader("content-disposition", "attachment; filename=" + fileName);52 response.ContentType = "application/octet-stream";53 response.BinaryWrite(file);54 response.Flush();55 56 }57 catch58 {59 60 }61 62 }63 }
对于要打印成pdf的html要求:
1. dom元素的 height/width/margin/padding以及定位,尽量使用百分比的形式。
2. 图片的像素质量尽量高一些,因为生成pdf的过程会有缩放。另外加入html的时候设置显示的高度跟宽度。
3. 对于pdf的分页,可以直接使用一些属性来实现:
<header page-break-before="always"></header>
{page-break-before:always;}//添加到header的dom元素实现换页
<footer page-break-after="always"></footer>
{page-break-after:always;} //添加到footer的dom元素实现换页
{page-break-inside:avoid;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。