在带有旋转功能的 asp.net core 2.1 应用程序中将 View 转换为 pdf 时出现错误
Value cannot be null. Parameter name: path1
下面是我的代码
var rpt = new ViewAsPdf();
//rptLandscape.Model = Model;
rpt.PageOrientation = Rotativa.AspNetCore.Options.Orientation.Landscape;
rpt.PageSize = Rotativa.AspNetCore.Options.Size.A4;
rpt.ViewName = "Test";
byte[] arr = await rpt.BuildFile(actionContextAccessor.ActionContext);
System.IO.File.WriteAllBytes(Path.Combine(env.WebRootPath, "PDFStorage", "File.pdf"), arr);
虽然它成功地以 pdf 格式返回网页,但我想将它存储在一个文件夹中。 此错误的可能原因是什么? ,我已经检查了所有,它甚至不包含名称为 name1 的属性
更新1:错误不在Path.Combine()中,错误在它之前的行中。
byte[] arr = await rpt.BuildFile(actionContextAccessor.ActionContext);
最佳答案
精简版
您需要在 Startup.cs
中调用 RotativaConfiguration.Setup(env);
并下载并部署另一个工具来进行实际转换工作。您可能应该找一个不同的库。
长版
如果没有实际的异常及其调用堆栈,人们只能猜测或检查 the source code并尝试猜测可能出了什么问题。
BuildFile 的源代码是:
public async Task<byte[]> BuildFile(ActionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
//if (this.WkhtmlPath == string.Empty)
// this.WkhtmlPath = context.HttpContext.Server.MapPath("~/Rotativa");
this.WkhtmlPath = RotativaConfiguration.RotativaPath;
var fileContent = await CallTheDriver(context);
if (string.IsNullOrEmpty(this.SaveOnServerPath) == false)
{
File.WriteAllBytes(this.SaveOnServerPath, fileContent);
}
return fileContent;
}
WriteAllBytes
不可能是罪魁祸首。不过,它确实设置了 RotativaConfiguration.RotativaPath
设置中的 WkhtmlPath
属性。 CallTheDriver()
中的调用显示该库仅调用带有一些开关的可执行文件来转换 PDF 文件。
actual call执行 exe,从 ViewAsPdf.cs
到 WkhtmlDriver.cs
是:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Path.Combine(wkhtmlPath, wkhtmlExe),
Arguments = switches,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = wkhtmlPath,
CreateNoWindow = true
}
};
proc.Start();
如果wkhtmlPath
为空,您将得到一个空参数异常。所有这些调用都会出现在异常的调用堆栈中。
解决方案是确保正确设置 RotativaConfiguration.RotativaPath
属性。 repo 协议(protocol)本身 explains that :
Basic configuration done in Startup.cs:
RotativaConfiguration.Setup(env);
Make sure you have a folder with the wkhtmltopdf.exe file accessible by the process running the web app. By default it searches in a folder named "Rotativa" in the root of the web app. If you need to change that use the optional parameter to the Setup call RotativaConfiguration.Setup(env, "path/relative/to/root")
顺便说一句,该库的作用是,在 web 应用程序 中运行单独的可执行文件是一个非常非常糟糕的主意:
- 失去了可扩展性。为每个请求运行一个单独的可执行文件是非常昂贵的并且很容易淹没繁忙的服务器。这就是生产服务器不以这种方式工作的原因。如果进程挂起,请求将被处理。您最终可能会遇到孤立的进程。
- 其次,它需要更高的权限 - 网络应用程序的帐户必须能够执行任意可执行文件,这是不应该被允许的。
最后,忘掉跨平台部署吧。可执行文件名称是 hard-coded到“wkhtmltopdf.exe”,即使 https://wkhtmltopdf.org/网站提供所有操作系统的版本。
顺便说一句,该工具本身提供了一个 C 库以供在其他应用程序中使用
关于c# - Rotativa.aspnetcore 中的 BuildFile 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51513393/