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

wkhtmltopdf 生成pdf

2014-06-28 12:55 246 查看
public class PdfHelper
{

static string RootPath
{
get
{
string AppPath = "";
HttpContext HttpCurrent = HttpContext.Current;
if (HttpCurrent != null)
{
AppPath = HttpCurrent.Server.MapPath("~");
}

return AppPath.Trim(new char[]{'\\'});
}
}

public static void GetPdf(HttpResponseBase response,string pdfUrl)
{
string fileName = Guid.NewGuid().ToString("N") + ".pdf";
string filePath = RootPath + "\\pdfs\\" + fileName;
string exePath=RootPath + "\\wkhtmltopdf\\wkhtmltopdf.exe";
string args=pdfUrl + " --zoom 1.25 \"" + filePath+"\"";

Process p =new Process();
p.StartInfo.FileName = exePath;
p.StartInfo.Arguments = args;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;

try
{
p.Start();
p.WaitForExit();
p.StandardOutput.ReadToEnd();
p.Close();

FileStream fs = new FileStream(filePath, 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);
response.ContentType = "application/octet-stream";
response.BinaryWrite(file);
response.Flush();

}
catch
{

}

}
}


对于要打印成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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: