
导出效果:
因为是基于wkhtmltopdf插件,所以服务器上都需安装一下wkhtmltopdf插件,并配置环境变量。
1、安装wkhtmltopdf插件 下载安装官网下载地址:https://wkhtmltopdf.org/downloads.html
按需下载对应的版本,安装即可。我的安装在 C:Program Files 下
网盘下载地址:https://pan.baidu.com/s/1LiTU5Q6FZopOCHB9740vrg
提取码:22nd
在系统的path变量中添加 “C:Program Fileswkhtmltopdfbin;”
注意:C:Program Fileswkhtmltopdf 为wkhtmltopdf的安装路径。我的安装在c盘 的 Program Files文件夹下
我为了省事做了一个html模板页,其实也可以不做,写在代码里也是一样的。
export_to_pdf.html
${CONTENT}
ExportToPDFHelper.cs
public static class ExportToPDFHelper
{
private static string exePath = System.Web.HttpContext.Current.Server.MapPath("\wkhtmltopdf\bin\wkhtmltopdf.exe");//执行命令的wkhtmltopdf.exe路径
///
/// HTML文本内容转换为PDF
///
/// HTML文本内容
/// 文件名
///
public static bool HtmlTextConvertToPdf(string strHtml, string exportFileName,string userMark = null)
{
bool flag = false;
try
{
string htmlPath = HtmlTextConvertFile(strHtml);
if (string.IsNullOrWhiteSpace(exportFileName))
exportFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 10000);
string fileName = exportFileName + ".pdf";
flag = HtmlConvertToPdf(htmlPath, fileName, "Portrait","A4",userMark);
if (File.Exists(htmlPath))
{
File.Delete(htmlPath);
}
}
catch
{
flag = false;
}
return flag;
}
///
/// HTML转换为PDF
///
/// 可以是本地路径,也可以是网络地址
/// PDF文件保存的路径
/// 纵向-Portrait 横向-Landscape
///
public static bool HtmlConvertToPdf(string htmlPath, string fileName, string orientation, string type = "A4", string userMark = null)
{
bool flag = false;
string filepath = System.Web.HttpContext.Current.Server.NewTempFilePath(fileName, userMark);
string savePathName = System.Web.HttpContext.Current.Server.MapPath(filepath);
if (File.Exists(savePathName))
{
File.Delete(savePathName);
}
///这个路径为程序集的目录,因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下
if (!File.Exists(exePath))
{
throw new Exception("No application wkhtmltopdf.exe was found.");
}
try
{
string Arguments = $"-q -B 0 -L 0 -R 0 -T 0 -O {orientation} -s {type} --no-background --disable-smart-shrinking {htmlPath} {savePathName}"; //参数可以根据自己的需要进行修改
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = exePath;
startInfo.Arguments = Arguments;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
using (var cc = Process.Start(startInfo))
{
cc.WaitForExit();
flag = true;
}
DownLoadFile(savePathName, fileName);
}
catch (Exception ex)
{
flag = false;
throw ex;
}
return flag;
}
///
/// HTML文本内容转HTML文件
///
/// HTML文本内容
/// HTML文件的路径
public static string HtmlTextConvertFile(string strHtml)
{
if (string.IsNullOrEmpty(strHtml))
{
throw new Exception("HTML text content cannot be empty.");
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("\FileTemp\" + DateTime.Today.ToString("yyyyMMdd"));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 10000) + ".html";
using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8))
{
streamWriter.Write(strHtml);
streamWriter.Flush();
}
};
return fileName;
}
catch
{
throw new Exception("HTML text content error.");
}
}
///
/// 下载文件
///
/// 物理路径文件
/// 下载的文件名
public static void DownLoadFile(string savePathName, string fileName)
{
if (File.Exists(savePathName))
{
FileInfo fi = new FileInfo(savePathName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
//HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
// HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
//加上HttpUtility.UrlEncode()方法,防止文件下载时,文件名乱码,(保存到磁盘上的文件名称应为“中文名.gif”) 已测试:IE、谷歌、火狐、360浏览器
//.Replace("+","%20") 空格转换后会变成+,这里将加密后+,替换成空格
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename*=UTF-8''" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+", "%20"));
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream;charset=utf-8";
HttpContext.Current.Response.WriteFile(savePathName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
fi.Delete();//将服务器文件删除
}
}
}
////// 打印模板内容 /// /// ///private string GetPrintTempContent(string tempFileName) { Encoding code = Encoding.GetEncoding("utf-8"); // 读取模板文件 string temp = Server.MapPath(string.Format("/PrintTemp/{0}", tempFileName)); StreamReader sr = null; string str = string.Empty; try { sr = new StreamReader(temp, code); str = sr.ReadToEnd(); // 读取文件 } catch (Exception ex) { sr.Close(); throw ex; } return str; } public void _ExportPDF(){ var str = GetPrintTempContent("export_to_pdf.html"); var fileName="2021年XXXXX名单"; var list = .....;//数据源 if (list != null && list.Count > 0) { StringBuilder sContent = new StringBuilder(); int x = 0, xh = 1, pageSize = 22;//每页显示条数 var total = list.Count;//总记录数 int num = total % pageSize == 0 ? (total / pageSize) : (total / pageSize + 1);//总页数 do { sContent.Append(""); sContent.AppendFormat(" {0}
", title); sContent.Append("
| 序号 | 学校名称 | 姓名 | 性别 | 证件号码 | 备注 | |
| {0} | {1} | {2} | {3} | {4} | {5} | {6} |