c# - 如何使用 wkhtmltopdf 将 html 作为字符串传递?

标签 c# asp.net wkhtmltopdf

如何使用 asp.net、c# 在 wkhtmltopdf 中将 html 作为字符串而不是 url 传递?

最佳答案

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

关于c# - 如何使用 wkhtmltopdf 将 html 作为字符串传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4651373/

相关文章:

pdf - Odoo8 Qweb 生成的 pdf 文档。第二页的表格行被卡住

c# - 使用 FastReport.Net 创建报告

没有方法重载的 c# 多态性(对于 web 方法)

c# - vb.net 相当于 "private void (string text)"

ruby-on-rails - ROR应用程序中的WKHTMLTOPDF路径

ruby-on-rails - PDFkit 在生成带有图像的 pdf 时挂起

c# - 如何在 C# 9 中将记录转换为元组

c# - 如何将字符串类型的对象动态转换为 T 类型的对象

c# - 用户控件中不允许使用文字内容

c# - 在提交表单之前执行方法