zoukankan      html  css  js  c++  java
  • 把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

  • 相关阅读:
    Go语言【第八篇】:Go语言变量作用域
    Go语言【第七篇】:Go函数
    Django 2.0 学习(10):Django 定制化
    Go语言【第六篇】:Go循环语句
    Go语言【第五篇】:Go条件语句
    Go语言【第四篇】:Go运算符
    Go语言【第二篇】:Go语法和数据类型
    苹果电脑自带python安装tensorflow一直有问题
    那些年深度学习所踩过的坑-第一坑
    C++基础知识--DAY3
  • 原文地址:https://www.cnblogs.com/gzh4455/p/2690733.html
Copyright © 2011-2022 走看看