【问题标题】:How to use wkHtmltoPdf to generate PDf files from statcic html files in C# [closed]如何使用 wkHtmltoPdf 从 C# 中的静态 html 文件生成 PDf 文件 [关闭]
【发布时间】:2020-01-09 07:14:16
【问题描述】:

谁能建议如何在 C# 控制台应用程序中使用 wkhtmltopdf 从静态 html 文件生成 PDF 文件?

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

我已尝试下载 ibwkhtmltox-0.11.0_rc1 Windows 静态库 (i368) 但不能将其 dll 包含到我的 c# 控制台应用程序中。

任何代码示例都会有所帮助

【问题讨论】:

    标签: c# wkhtmltopdf


    【解决方案1】:

    查看此项目github.com/gmanny/Pechkin,它是 wkhtmlpdf 的包装器,但由于它不作为可执行文件运行,因此您应该更容易让它在共享主机上运行。

    【讨论】:

    • 请不要发单个链接
    【解决方案2】:

    我正在通过 Pechkin 的 C# 端口使用 WkHtmlToPdf 进行中间实现 - 到目前为止,我看到了一些很好的结果(除了使用 SSL 从站点调用动态生成的 PDF 时出现的一个相当奇怪的问题)但是对于更基本的实现来说,它很棒!使用 NuGet 将 Pechkin 加入您的项目,然后使用以下代码!

    byte[] pdf = new Pechkin.Synchronized.SynchronizedPechkin(
    new Pechkin.GlobalConfig()).Convert(
        new Pechkin.ObjectConfig()
       .SetLoadImages(true)
       .SetPrintBackground(true)
       .SetScreenMediaType(true)
       .SetCreateExternalLinks(true), html);
    
    using (FileStream file = System.IO.File.Create(@"C:\TEMP\Output.pdf"))
    {
        file.Write(pdf, 0, pdf.Length);
    }
    

    【讨论】:

      【解决方案3】:

      如果可以的话,我建议您使用 exe - 我认为它更简单。

      例如,查看Derp class in another answer of mine,了解如何从 C# 运行 wkhtmltopdf exe。或者试试下面的 untested 代码(你的真实代码会更复杂,这只是一个演示/POC)。只需将 google.com 替换为您想要的 HTML 页面 - 您也可以使用本地文件。

      var pi = new ProcessStartInfo(@"c:\wkhtmltopdf\wkhtmltopdf.exe");
      pi.CreateNoWindow = true;
      pi.UseShellExecute = false;
      pi.WorkingDirectory = @"c:\wkhtmltopdf\";
      pi.Arguments = "http://www.google.com gogl.pdf";
      
      using (var process = Process.Start(pi))
      {
          process.WaitForExit(99999);
          Debug.WriteLine(process.ExitCode);
      }
      

      (从https://stackoverflow.com/a/11992062/694325重复回答)

      【讨论】:

      • 为什么是-1?我知道这可能不适用于每种情况的每种解决方案,但评论会很好:X。
      【解决方案4】:

      这会对你有所帮助........尝试一次。

         protected static byte[] Convert(string wkhtmlPath, string switches, string html, string wkhtmlExe)
          {       
              // generate PDF from given HTML string, not from URL
              if (!string.IsNullOrEmpty(html))
              {               
                  html = SpecialCharsEncode(html);
              }
      
              var proc = new Process();
      
              var StartInfo = new ProcessStartInfo();
      
              proc.StartInfo.FileName = Path.Combine(wkhtmlPath, wkhtmlExe);
              proc.StartInfo.Arguments = switches;
              proc.StartInfo.UseShellExecute = false;
              proc.StartInfo.RedirectStandardOutput = true;
              proc.StartInfo.RedirectStandardError = true;
              proc.StartInfo.RedirectStandardInput = true;
              proc.StartInfo.WorkingDirectory = wkhtmlPath;
      
              proc.Start();
      
              // generate PDF from given HTML string, not from URL
              if (!string.IsNullOrEmpty(html))
              {
                  using (var sIn = proc.StandardInput)
                  {
                      sIn.WriteLine(html);
                  }
              }
      
              var ms = new MemoryStream();
      
              using (var sOut = proc.StandardOutput.BaseStream)
              {                              
                  byte[] buffer = new byte[4096];
                  int read;
      
                  while ((read = sOut.Read(buffer, 0, buffer.Length)) > 0)
                  {
                      ms.Write(buffer, 0, read);
                  }
              }
      
              string error = proc.StandardError.ReadToEnd();
      
              if (ms.Length == 0)
              {
                  throw new Exception(error);
              }
      
              proc.WaitForExit();
      
              return ms.ToString(); 
          }
      
      
          /// <summary>
          /// Encode all special chars
          /// </summary>
          /// <param name="text">Html text</param>
          /// <returns>Html with special chars encoded</returns>
          private static string SpecialCharsEncode(string text)
          {
              var chars = text.ToCharArray();
              var result = new StringBuilder(text.Length + (int)(text.Length * 0.1));
      
              foreach (var c in chars)
              {
                  var value = System.Convert.ToInt32(c);
                  if (value > 127)
                      result.AppendFormat("&#{0};", value);
                  else
                      result.Append(c);
              }
      
              return result.ToString();
          }
      
      
      }
      

      这里我们返回内存流,我们还需要添加header,内容类型

         public override void ExecuteResult(ControllerContext context)
          {
             // this.FileName = context.RouteData.GetRequiredString("action");
      
              var fileContent =  Convert(wkhtmltopdfPath, switches, null, wkhtmlExe);
      
              var response = this.PrepareResponse(context.HttpContext.Response);
      
              response.OutputStream.Write(fileContent, 0, fileContent.Length);
          }
      
          protected HttpResponseBase PrepareResponse(HttpResponseBase response)
          {
              response.ContentType = this.GetContentType();
              this.FileName = "YourFile.pdf";
              if (!String.IsNullOrEmpty(this.FileName))
              response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", SanitizeFileName(this.FileName)));
              response.AddHeader("Content-Type", this.GetContentType());
      
              return response;
          }
      

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 2012-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-17
        • 2010-11-22
        相关资源
        最近更新 更多