最近项目需要使用到html转PDF,如翻阅了很多资料,自己整理了如下的内容做个笔记
博客:https://www.jianshu.com/p/559c594678b6
官方下载:https://wkhtmltopdf.org/downloads.html
我们一起踩过一坑:https://blog.csdn.net/qq_39541254/article/details/107541497
asp.net转换实例:https://www.cnblogs.com/ztf20/archive/2004/01/13/10414832.html
1、下载好 默认安装路径:C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
2、根据情况把你安装wkhtmltopdf目录下的bin子目录加到 PATH 环境变量
3、导入类pdfconvert.cs 设计web.config 的wkhtmltopdf.exe路径如下
<configuration>
<appSettings>
<add key="wkhtmltopdf:path" value="C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"/>
</appSettings>
</configuration>
4、定义css类分页,增加qrcode.min.js 二维码连接,引入JS jquery.min.js 如下代码 增加生成动态二维码方法
string str = string.Format(@"<style>div{0}</style> <script src=""Scripts/jquery.min.js""></script><script src=""Scripts/qrcode.min.js""></script><script>{1}</script><div id=""tpdf"">", "{page-break-before:always;font-size:8px;}", "function makeCode(_div,str){var qrcode = new QRCode(document.getElementById(_div),{width:80,height:80});qrcode.makeCode(str);}");
5、后台动态接拼代码 :
for (int i = 0; i < 100; i++)
{
str += string.Format(@"<div id=""qrcode{0}"" >測試" + i.ToString()+"</div>",i.ToString());
endstr += string.Format(@"makeCode(""qrcode{0}"",""{1}"");", i.ToString(),i.ToString());
}
endstr += "</script>";
6、调用转pdf方法
PdfConvert.ConvertHtmlToPdf(
new PdfDocument { Html = str,
Pageheight="80mm", //页面尺码
Pagewidth="30mm", //页面尺码
marginbottom="0mm", //边距
marginleft = "0mm",
marginright = "0mm",
margintop = "0mm"
},
new PdfOutput { OutputFilePath = outpath }, true
);
7、整个调用方法如下
protected void Button3_Click(object sender, EventArgs e)
{
string url = @"https://www.baidu.com";
string filename = Guid.NewGuid().ToString();
string pdfpath = filename + ".pdf";
string outpath = Server.MapPath(pdfpath);
Console.InputEncoding = Encoding.UTF8;
PdfConvert.Environment.Debug = false;
string endstr = "<script>";
string str = string.Format(@"<style>div{0}</style><script src=""Scripts/jquery.min.js""></script><script src=""Scripts/qrcode.min.js""></script><script>{1}</script>", "{page-break-before:always;font-size:8px;}", "function makeCode(_div,str){var qrcode = new QRCode(document.getElementById(_div),{width:80,height:80});qrcode.makeCode(str);}");
for (int i = 0; i < 100; i++)
{
str += string.Format(@"<div id=""qrcode{0}"" >測試" + i.ToString()+"</div>",i.ToString());
endstr += string.Format(@"makeCode(""qrcode{0}"",""{1}"");", i.ToString(),i.ToString());
}
endstr += "</script>";
str += endstr;
str11 = str;
PdfConvert.ConvertHtmlToPdf(
new PdfDocument { Html = str,
Pageheight="80mm",
Pagewidth="30mm",
marginbottom="0mm",
marginleft = "0mm",
marginright = "0mm",
margintop = "0mm"
},
new PdfOutput { OutputFilePath = outpath }, true
);
Response.Redirect(pdfpath); //转换后直接打开
}
protected void Page_Load(object sender, EventArgs e)
{
Button3.Attributes.Add("onclick", "this.form.target='_blank'");
}
###################################################################
动态数据转换成PDF当方法:
<script type="text/javascript">
document.getElementById("downpdf").onclick = function (){
var pages = document.querySelector('#divElehtml').children;//转PDF档起始元素divEle ID
console.log(pages[1].outerHTML);
var str = "";
for (var i = 0; i < pages.length; i++) {
str += pages[i].outerHTML;
}
console.log(str);
$.ajax({
type: "post",
url: "./html2pdf/html2pdf.ashx",
async: false,//同步
data: {
Method: 'ExceclPDF2',
HtmlStr:encodeURIComponent(str),//注意这里必须要进行转码,负责Ajax会报错 (已经把+号变成空格了) encodeURI会造成空格就成+号,请用encodeURIComponent
},
success: function (result) {
//获取返回参数
if (result != undefined && result != "") {
//请求下载pdf的url
// window.location.href = result;
window.open(result);
}
}
});
}
</script>
html2pdf.ashx代码如下
----------------------------------------------------------------------------------------------------------
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string ssss = Convert.ToString(context.Request.Params["HtmlStr"]);
int MaxAndln = Convert.ToInt32(context.Request.Params["MaxAndln"].ToString());//订单编号与裁床单ID
string htmlStr = HttpUtility.UrlDecode(ssss);
string htmlfileName = "html2pdf" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
string htmlSavPath = context.Request.MapPath("~/slip/print/HtmlFile/" + htmlfileName);
string html = @"<html xmlns=""http://www.w3.org/1999/xhtml"" > <head runat=""server"" ></head><body>" + htmlStr + "</body></html>