Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用wkHtmltoPdf从C中的statcic html文件生成PDf文件#_C#_Wkhtmltopdf - Fatal编程技术网

C# 如何使用wkHtmltoPdf从C中的statcic html文件生成PDf文件#

C# 如何使用wkHtmltoPdf从C中的statcic html文件生成PDf文件#,c#,wkhtmltopdf,C#,Wkhtmltopdf,有人能建议如何在C#控制台应用程序中使用wkhtmltopdf从静态html文件生成PDF文件吗 wkhtmltopdf- 我已尝试下载ibwkhtmltox-0.11.0rc1 Windows静态库(i368) 但不能将其dll包含到我的c#控制台应用程序中 如果可以的话,任何代码示例都会很有帮助。我建议使用exe-我认为它更简单 例如,查看有关如何从C#运行wkhtmltopdf exe的。或者尝试下面的未测试的代码(您真正的代码会更复杂,这只是一个演示/POC)。只要用你想要的HTML页面

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

wkhtmltopdf-

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


如果可以的话,任何代码示例都会很有帮助。我建议使用exe-我认为它更简单

例如,查看有关如何从C#运行wkhtmltopdf exe的。或者尝试下面的未测试的代码(您真正的代码会更复杂,这只是一个演示/POC)。只要用你想要的HTML页面替换google.com,你也可以使用本地文件

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);
}

(答案重复自)

查看此项目,它是wkhtmlpdf的包装器,但由于它不是作为可执行文件运行的,因此您应该可以更轻松地在共享主机上运行它

我正在通过Pechkin的C#port使用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);
}

这将帮助你。。。。。。。。。。试试看

   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();
    }


}

请不要发布单个链接为什么-1?我理解这可能不适合每种情况下的每种解决方案,但最好给出一个注释:X。
   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;
    }