Convert HTML to PDF in C# using wkhtmltopdf

It is a simple shell utility created in C# to convert html to pdf using the webkit rendering engine, and it is free. But it has strange codes when converting HTML pages in GB2132-code to PDF.

http://code.google.com/p/wkhtmltopdf/


Code Snippet
  1. /// <summary>
  2. /// Convert html to pdf document.
  3. /// </summary>
  4. ///<param name="url">URL address</param>
  5.   ///<param name="path">PDF save load</param>
  6. public static bool HtmlToPdf(string url, string path)
  7. {        
  8.             try
  9.     {
  10.        if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
  11.            return false;   
  12.        Process p = new Process();
  13.        string str = System.Web.HttpContext.Current.Server.MapPath("wkhtmltopdf.exe");
  14.             
  15.        if (!System.IO.File.Exists(str))
  16.            return false;
  17.        p.StartInfo.FileName = str;
  18.        p.StartInfo.Arguments = " \"" + url + "\" " + path;
  19.        p.StartInfo.UseShellExecute = false;
  20.        p.StartInfo.RedirectStandardInput = true;
  21.         p.StartInfo.RedirectStandardOutput = true;
  22.         p.StartInfo.RedirectStandardError = true;
  23.         p.StartInfo.CreateNoWindow = true;
  24.         p.Start();
  25.         System.Threading.Thread.Sleep(500);
  26.         return true;
  27.     }
  28.     catch (Exception ex)
  29.     {
  30.         HttpContext.Current.Response.Write(ex);
  31.     }
  32.     return false;
  33. }

Post a Comment