我正在尝试生成 PDF,它在开发中完美运行,但在我的生产服务器上却不行。我认为这是一个权限问题。我得到的错误是:
值不能为空。参数名称:文件内容
我假设它正在谈论这个 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();
}
}