首页/电脑软件/ 使用wkhtmltopdf第三方包将HTML转为PDF的程序

使用wkhtmltopdf第三方包将HTML转为PDF的程序

作者:神奇   分类:电脑软件   时间:2021-12-23 20:14:40  标签:


1、这里使用的wkhtmltopdf.exe第三方包辅助(下载方式贴到最下方)
2、废话不多少直接上代码(直接运行,亲自试过)
[C#] 纯文本查看 复制代码public static bool HtmlConvertToPdf(string htmlPath, string savePath) { bool flag = false; CheckFilePath(savePath); ///这个路径为程序集的目录,因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe"; 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(60000); ///用于查看是否返回错误信息 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; }private static 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."); } }private static 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."); } }// 在main函数直接调用HtmlConvertToPdf(htmlPath, savePath);
wkhtmltopdf.exe下载方式:
https://wkhtmltopdf.org/downloads.html 点击选择自己的版本,这里帖主选择的是win64的
温馨提示如有转载或引用以上内容之必要,敬请将本文链接作为出处标注,谢谢合作!

评论:

发表评论:

code