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的 |