把HTML生成PDF

一般来说可以生成一般的不需要用户及密码验证,可以很简单地实现功能,下面贴的代码是对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文件

https://files.cnblogs.com/gzh4455/wkhtmltopdf.zip

原文地址:https://www.cnblogs.com/gzh4455/p/2690733.html