直接将html转换成pdf,用过其他的几种方式效果相当的不理想。最后找到wkhtmltopdf转换pdf效果还比较好,以下是解决方案。
第一步:下载wkhtmltopdf,加压并找到wkhtmltopdf.exe文件,可以将wkhtmltopdf.exe文件放到任意位置,建议放到程序的根目录中。
第二步:通过c#进程调用wkhtmltopdf.exe将html转换成pdf文件。以下是转换方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using System.Configuration; namespace GH.TechnicalSupervision.BLL2 { public class PdfHelper { /// <summary> /// HTML转换为PDF /// </summary> /// <param name="htmlPath">可以是本地路径,也可以是网络地址</param> /// <param name="savePath">PDF文件保存的路径</param> /// <returns></returns> public bool HtmlConvertToPdf( string pdfExePath, string htmlPath, string savePath) { bool flag = false ; CheckFilePath(savePath); ///这个路径为程序集的目录,因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下 //string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";""; //string exePath = "C:\\Program Files (x86)\\wkhtmltopdf\\bin\\wkhtmltopdf.exe"; string exePath = pdfExePath; if (!File.Exists(exePath)) { throw new Exception( "No application wkhtmltopdf.exe was found." ); } try { ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = exePath; processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath); processStartInfo.UseShellExecute = false ; processStartInfo.CreateNoWindow = true ; processStartInfo.RedirectStandardInput = true ; processStartInfo.RedirectStandardOutput = true ; processStartInfo.RedirectStandardError = true ; processStartInfo.Arguments = GetArguments(htmlPath, savePath); Process process = new Process(); process.StartInfo = processStartInfo; process.Start(); process.WaitForExit(); ///用于查看是否返回错误信息 //StreamReader srone = process.StandardError; //StreamReader srtwo = process.StandardOutput; //string ss1 = srone.ReadToEnd(); //string ss2 = srtwo.ReadToEnd(); //srone.Close(); //srone.Dispose(); //srtwo.Close(); //srtwo.Dispose(); process.Close(); process.Dispose(); flag = true ; } catch { flag = false ; } return flag; } /// <summary> /// 获取命令行参数 /// </summary> /// <param name="htmlPath"></param> /// <param name="savePath"></param> /// <returns></returns> private string GetArguments( string htmlPath, string savePath) { if ( string .IsNullOrEmpty(htmlPath)) { throw new Exception( "HTML local path or network address can not be empty." ); } if ( string .IsNullOrEmpty(savePath)) { throw new Exception( "The path saved by the PDF document can not be empty." ); } StringBuilder stringBuilder = new StringBuilder(); //stringBuilder.Append(" --page-height 100 "); //页面高度100mm //stringBuilder.Append(" --page-width 100 "); //页面宽度100mm //stringBuilder.Append(" --header-center 我是页眉 "); //设置居中显示页眉 //stringBuilder.Append(" --header-line "); //页眉和内容之间显示一条直线 //stringBuilder.Append(" --footer-center \"Page [page] of [topage]\" "); //设置居中显示页脚 //stringBuilder.Append(" --footer-line "); //页脚和内容之间显示一条直线 stringBuilder.Append( " " + htmlPath + " " ); //本地 HTML 的文件路径或网页 HTML 的URL地址 stringBuilder.Append( " " + savePath + " " ); //生成的 PDF 文档的保存路径 return stringBuilder.ToString(); } /// <summary> /// 验证保存路径 /// </summary> /// <param name="savePath"></param> private void CheckFilePath( string savePath) { string ext = string .Empty; string path = string .Empty; string fileName = string .Empty; ext = Path.GetExtension(savePath); if ( string .IsNullOrEmpty(ext) || ext.ToLower() != ".pdf" ) { throw new Exception( "Extension error:This method is used to generate PDF files." ); } fileName = Path.GetFileName(savePath); if ( string .IsNullOrEmpty(fileName)) { throw new Exception( "File name is empty." ); } try { path = savePath.Substring(0, savePath.IndexOf(fileName)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch { throw new Exception( "The file path does not exist." ); } } } } |
注意:转换的网页的字体有可能wkhtmltopdf不识别,导致转换后的pdf文件出现乱码。比如“宋体”不识别,但是“新宋体”能识别。
标签:
pdf
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2016-02-23 IIS应用程序池自动回收问题的有效解决办法