一般來說可以生成一般的不需要用戶及密碼驗證,可以很簡單地實現功能,下面貼的代碼是對Based Windows Authentication的頁面生成PDF(我的是基於SharePoint的)
代碼如下:
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, "【頁面密碼】", "【頁面登陸的用戶名】"); 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.baidu.com", "buidu1")
但有可能會出現亂碼的問題,可能有兩種方法,第一,在代碼修改,但現在由於項目沒有要求,暫時沒有研究,第二種,如果是你本身的頁面,那么可以修改本身頁面的編碼方式
你可以從以下網址下載wkhtmltopdf.exe文件
