1.准备:
下载wkhtmltopdf.exe软件,
?
2.前端代码
参数div为需要打印部分的div整个元素内容;
$.ajax({
type: "post",
url: "./html2pdf.ashx?m=HtmlToPDF",
dataType: "json",
data: { div:encodeURI(div)},
success: function (data) {
console.log(data)
}
});
3.后端代码
using System.Diagnostics;
using System.Web;
using System.IO;
using System;
using HtmlAgilityPack;
public string HtmlToPDF(HttpContext context)
{
string filename = DateTime.Now.ToString("yyyyMMddhhmmss");
//获取要打印的节点页面div元素内容
string div= context.Request["div"] == null ? "" : context.Request["div"].ToString();
string content = HttpUtility.UrlDecode(div);
//将需要打印的内容转为html对象
var printHtmlDoc= new HtmlDocument();
printHtmlDoc.LoadHtml(content);
//加载模板html文件
var templateHtml = @"http://localhost/JJLBSWEB/JJLBSResource/Page/Default/WorkSummary/test.html";
HtmlWeb web = new HtmlWeb();
var templateHtmlDoc = web.Load(templateHtml);
//获取body节点
var templateHtmlBody = templateHtmlDoc.DocumentNode.SelectSingleNode("//body");
HtmlNodeCollection children = new HtmlNodeCollection(templateHtmlBody);
children.Add(printHtmlDoc.DocumentNode);
//将要打印的节点页面div添加到body元素里
templateHtmlBody.AppendChildren(children);
//获取整个html文件内容字符串
//string s =templateHtmlDoc.DocumentNode.InnerHtml;
//var htmlDoc2 = new HtmlDocument();
//htmlDoc2.LoadHtml(s);
string dovSavePath = @"E:\*\" + filename + ".html";
TextWriter tw = File.CreateText(dovSavePath);
templateHtmlDoc.Save(tw);
string exePath = "D:\\wkhtmltox\\bin\\wkhtmltopdf.exe";
string url = "http://localhost/*/"+filename+".html";//html页面url
//生成pdf文件路径
string pdfUrl = "D:\\"+ filename + ".pdf";//PDF存储的地址
//生成pdf文件
ProcessStartInfo processStartInfo = new ProcessStartInfo();//指定启动进程时使用的一组值。
processStartInfo.FileName = exePath;
processStartInfo.UseShellExecute = false;
processStartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(exePath);
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = false;
processStartInfo.Arguments = " " + url + " " + pdfUrl;
Process process = new Process();
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit(120000);
process.Close();
process.Dispose();
return "";
}
|