把HTML生成PDF
对页面生成PDF
public bool HtmlToPdf(string url, string path) { try { string filename = PdfFolder + "\\" + path + ".pdf"; Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"C:\PDFFolder\wkhtmltopdf.exe"; //p.StartInfo.UserName = "administrator"; //用户名 //p.StartInfo.Password = StringToSecureString("password01!");//用户密码 // p.StartInfo.Arguments = " " + "\"" + url + "\"" + " " + "\"" + filename + "\""; p.StartInfo.Arguments = string.Format(" \"{0}\" \"{1}\" --password \"{2}\" --username \"{3}\"", url, filename, "domain\password", "password"); p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none p.StartInfo.WorkingDirectory = "c:\\PDFFolder"; p.Start(); // read the output here... string output = p.StandardOutput.ReadToEnd(); // ...then wait n milliseconds for exit (as after exit, it can't read the output) p.WaitForExit(60000); // read the exit code, close process int returnCode = p.ExitCode; p.Close(); // if 0 or 2, it worked (not sure about other values, I want a better way to confirm this) return (returnCode == 0 || returnCode == 2); } catch (Exception ex) { } return false; } public static SecureString StringToSecureString(String str) { SecureString secureStr = new SecureString(); char[] chars = str.ToCharArray(); for (int i = 0; i < chars.Length; i++) { secureStr.AppendChar(chars[i]); } return secureStr; }
用法:HtmlToPdf("http://www.xxxxx.com", "xxxxx")
wkhtmltopdf.exe文件地址: http://pan.baidu.com/s/1gdF1eU3