wkhtmltopdf在MVC 4中不能为空

本文关键字:不能 MVC wkhtmltopdf | 更新日期: 2023-09-27 18:03:10

我正在尝试生成一个PDF,它在开发中工作完美,但不是在我的生产服务器上。我想这是许可的问题。我得到的错误是:

Value不能为空。参数名称:fileContents

我假设它说的是这个fileContents参数:

   System.Web.Mvc.Controller.File(Byte[] fileContents, String contentType, String fileDownloadName) +28

方法的代码是:

    public ActionResult Pdf(Guid id, string filename)
    {
        string url = Url.Action("RenderReport", "TitleSearchReport", new { id = id }, "http");
        var file = WKHtmlToPdf(url);
        return File(file, "application/pdf", Server.UrlEncode(filename));
    }

生成文件的代码是:

    public byte[] WKHtmlToPdf(string url)
    {
        var fileName = " - ";
        //var wkhtmlDir = "C:''Program Files''wkhtmltopdf''";
        //var wkhtml = "C:''Program Files''wkhtmltopdf''wkhtmltopdf.exe";
        var wkhtmlDir = HttpContext.Server.MapPath(@"~/wkhtmltopdf");
        var wkhtml = HttpContext.Server.MapPath(@"~/wkhtmltopdf/wkhtmltopdf.exe");
        var p = new Process();
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.FileName = wkhtml;
        p.StartInfo.WorkingDirectory = wkhtmlDir;
        string switches = "";
        switches += "--print-media-type ";
        switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
        switches += "--page-size Letter ";
        p.StartInfo.Arguments = switches + " " + url + " " + fileName;
        p.Start();
        //read output
        byte[] buffer = new byte[32768];
        byte[] file;
        using (var ms = new MemoryStream())
        {
            while (true)
            {
                int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                {
                    break;
                }
                ms.Write(buffer, 0, read);
            }
            file = ms.ToArray();
        }
        // wait or exit
        p.WaitForExit(60000);
        // read the exit code, close process
        int returnCode = p.ExitCode;
        p.Close();
        return returnCode == 0 ? file : null;
    }

同样,它在调试时工作得很好,但在部署时却不行。我怎么做才能使它在生产中发挥作用?

谢谢你的建议。

编辑:

改变了我的方法,但现在我得到的是一个空白页…

    public void Pdf(Guid id, string filename)
    {
        string url = Url.Action("RenderReport", "TitleSearchReport", new { id = id }, "http");
        var file = WKHtmlToPdf(url);
        if (file != null)
        {
            Response.ContentType = "Application/pdf";
            Response.BinaryWrite(file);
            Response.End();
        }
    }

wkhtmltopdf在MVC 4中不能为空

解决方案是为网络用户向我的根应用读写权限。不确定安全影响…