0

誰かがC#コンソールアプリケーションでwkhtmltopdfを使用して静的htmlファイルからPDFファイルを生成する方法を提案できますか?

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

ibwkhtmltox-0.11.0_rc1 Windows静的ライブラリ(i368)をダウンロードしようとしましたが、そのdllをc#コンソールアプリに含めることができません。

コードサンプルは役に立ちます

4

4 に答える 4

6

このプロジェクト github.com/gmanny/Pechkin を確認してください。これはwkhtmlpdfのラッパーですが、実行可能ファイルとして実行されないため、共有ホストで実行する方が簡単なはずです。

于 2012-10-01T04:55:27.763 に答える
3

私は、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);
}
于 2012-11-07T13:11:06.003 に答える
2

可能であれば、exe を使用することをお勧めします。簡単だと思います。

たとえば、C# から wkhtmltopdf exe を実行する方法に関する私の別の回答で Derp クラスを確認してください。または、以下のテストされていないコードのようなものを試してください(実際のコードはより複雑になります。これは単なるデモ/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から繰り返されます)

于 2012-09-21T21:00:48.887 に答える
0

これはあなたを助けます........一度試してみてください。

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


}

ここでメモリ ストリームを返します。さらにヘッダー、コンテンツ タイプを追加する必要があります。

   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;
    }
于 2016-06-03T07:36:31.353 に答える