记录一个将html页面转换成PDF文件的转换器,该转换器功能强大,且对于页面上的css,js等在转换过程中不会丢失,效果很棒!
转换器下载地址:wkhtmltopdf(官网)
同时附上C#将html转换为PDF的代码:
//生成PDF
string page= "~/Student/Print_StudentCard.aspx";//要打印的页面
string pdf = Server.MapPath("~/Upload/wkhtmltox/wkhtmltox/bin/wkhtmltopdf.exe");//转换器路径
string pdfpath = "~/Student/Card.pdf";//生成的PDF文件路径
//参数中\"表示字符",注意参数"生成的PDF文件路径"要保留双引号
Process p = System.Diagnostics.Process.Start(pdf, " -O Landscape " + page+ " \"" + Server.MapPath(pdfpath) + "\"");//-O 指定页面布局为横向或纵向
p.WaitForExit();
//下载PDF
//方法1,使用下面代码,在线打开
Response.Redirect(pdfpath);
//方法2,使用下面代码,让客户下载
Down(Server.MapPath(pdfpath), "考生信息.pdf");
//下载
public void Down(string filename, string fileDownName)//参数为:下载的文件全路径,下载保存时的文件名
{
Response.ClearContent();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename=" + fileDownName);
Response.TransmitFile(filename);
Response.Flush();
}
以上代码只是一个demo,具体使用时还请根据实际情况修改
当然wkhtmltopdf也为我们提供了很多参数,可以更好的达到转换效果,程序的使用说明:前往查看