25

asp.net、c#を使用してwkhtmltopdfでurlの代わりにhtmlを文字列として渡す方法は?

4

3 に答える 3

38

この例では STDIn と STDOut がリダイレクトされているため、ファイルはまったく必要ありません。

public static class Printer
{
    public const string HtmlToPdfExePath = "wkhtmltopdf.exe";

    public static bool GeneratePdf(string commandLocation, StreamReader html, Stream pdf, Size pageSize)
    {
        Process p;
        StreamWriter stdin;
        ProcessStartInfo psi = new ProcessStartInfo();

        psi.FileName = Path.Combine(commandLocation, HtmlToPdfExePath);
        psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName);

        // run the conversion utility
        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        // note: that we tell wkhtmltopdf to be quiet and not run scripts
        psi.Arguments = "-q -n --disable-smart-shrinking " + (pageSize.IsEmpty? "" : "--page-width " + pageSize.Width +  "mm --page-height " + pageSize.Height + "mm") + " - -";

        p = Process.Start(psi);

        try {
            stdin = p.StandardInput;
            stdin.AutoFlush = true;
            stdin.Write(html.ReadToEnd());
            stdin.Dispose();

            CopyStream(p.StandardOutput.BaseStream, pdf);
            p.StandardOutput.Close();
            pdf.Position = 0;

            p.WaitForExit(10000);

            return true;
        } catch {
            return false;

        } finally {
            p.Dispose();
        }
    }

    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[32768];
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {
            output.Write(buffer, 0, read);
        }
    }
}
于 2011-07-22T07:42:15.457 に答える
16

STDIN をリダイレクトすることは、おそらく、あなたがしようとしていることを達成するための最も簡単な方法です。

(ASP.Net で) wkhtmltopdf を使用して STDIN をリダイレクトする 1 つの方法は次のとおりです。

    private void WritePDF(string HTML)
    {
        string inFileName,
                outFileName,
                tempPath;
        Process p;
        System.IO.StreamWriter stdin;
        ProcessStartInfo psi = new ProcessStartInfo();

        tempPath = Request.PhysicalApplicationPath + "temp\\";
        inFileName = Session.SessionID + ".htm";
        outFileName = Session.SessionID + ".pdf";

        // run the conversion utility
        psi.UseShellExecute = false;
        psi.FileName = "c:\\Program Files (x86)\\wkhtmltopdf\\wkhtmltopdf.exe";
        psi.CreateNoWindow = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        // note that we tell wkhtmltopdf to be quiet and not run scripts
        // NOTE: I couldn't figure out a way to get both stdin and stdout redirected so we have to write to a file and then clean up afterwards
        psi.Arguments = "-q -n - " + tempPath + outFileName;

        p = Process.Start(psi);

        try
        {
            stdin = p.StandardInput;
            stdin.AutoFlush = true;

            stdin.Write(HTML);
            stdin.Close();

            if (p.WaitForExit(15000))
            {
                // NOTE: the application hangs when we use WriteFile (due to the Delete below?); this works
                Response.BinaryWrite(System.IO.File.ReadAllBytes(tempPath + outFileName));
                //Response.WriteFile(tempPath + outFileName);
            }
        }
        finally
        {
            p.Close();
            p.Dispose();
        }

        // delete the pdf
        System.IO.File.Delete(tempPath + outFileName);
    }

上記のコードは、アプリケーション ディレクトリに使用可能な一時ディレクトリがあることを前提としていることに注意してください。また、IIS プロセスの実行時に使用するユーザー アカウントに対して、そのディレクトリへの書き込みアクセスを明示的に有効にする必要があります。

于 2011-01-10T21:05:34.023 に答える
3

これが古い投稿であることは承知していますが、将来の開発者にはこのオプションが必要です。私も同じニーズを持っていました.Webアプリ内でPDFを取得するためだけにバックグラウンドプロセスを開始する必要があるという考えはひどいものです.

ここに別のオプションがあります: https://github.com/TimothyKhouri/WkHtmlToXDotNet

これは、wkhtmltopdf の .NET ネイティブ ラッパーです。

サンプルコードはこちら:

var pdfData = HtmlToXConverter.ConvertToPdf("<h1>COOOL!</h1>");

現時点ではスレッドセーフではないことに注意してください-私はそれに取り組んでいます。だから、モニターか何かか、ロックを使ってください。

于 2014-12-23T16:02:34.360 に答える