Jac*_*jer 0 pdf-generation wkhtmltopdf asp.net-core razor-pages
我有一个使用 .net core 3.1 Razor Pages 构建的 Web 应用程序。我需要添加功能以从视图生成 PDF。通常该库正在工作,因为我可以生成静态 PDF,但是当我想使用模型为模板做种时会出现问题。
该PageModel如下所示:
public class DetailsPdfModel : PageModel
{
private readonly ICablesData cablesData;
private readonly IConfiguration configuration;
public DetailsPdfModel(ICablesData cablesData, IConfiguration configuration)
{
this.cablesData = cablesData;
this.configuration = configuration;
}
public Cable Cable { get; set; }
public IActionResult OnGet(int cableId)
{
Cable = cablesData.GetById(cableId);
if (Cable == null)
{
return RedirectToPage("NotFound");
}
else
{
return new ViewAsPdf("DetailsPdf", this);
}
}
}
Run Code Online (Sandbox Code Playgroud)
视图如下所示:
@page
@model DetailsPdfModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DetailsPdf</title>
</head>
<body>
<p>@Model.Cable.Name</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我尝试获取 pdf 时发生异常。我注意到@Model总是null. 如果我改变return new ViewAsPdf("DetailsPdf", this);到return Page();的@Model不是null,但之后,这只是普通视图中不PDF文件。
任何想法如何解决这个问题?
如果我更改 return new ViewAsPdf("DetailsPdf", this); 返回 Page(); @Model 不为空,但之后只是常规视图而不是 pdf 文件。
那是因为ViewAsPdf不是为 Razor Page 设计的。并且Rotativa不公开 RazorPage 的内置 API。更多详细信息,请参见Rotativa.AspNetCore 的源代码。
作为一种解决方法,您可以创建一个自定义RazorPageAsPdf类来实现与以下相同的目标:
公共类 DetailsPdfModel : PageModel
{
...
public IActionResult OnGet(int cableId)
public RazorPageAsPdf OnGet(int cableId)
{
Cable = cableData.GetById(cableId);
如果(电缆 == 空)
{
return RedirectToPage("NotFound");
}
别的
{
return new ViewAsPdf("DetailsPdf", this);
返回新的 RazorPageAsPdf(this); // 我们不需要页面路径,因为它可以由当前路由确定
}
}
}
这是我的 RazorPageAsPdf 实现供您参考:
public class DetailsPdfModel : PageModel
{
...
public IActionResult OnGet(int cableId)
public RazorPageAsPdf OnGet(int cableId)
{
Cable = cablesData.GetById(cableId);
if (Cable == null)
{
return RedirectToPage("NotFound");
}
else
{
return new ViewAsPdf("DetailsPdf", this);
return new RazorPageAsPdf(this); // we don't need page path because it can be determined by current route
}
}
}
| 归档时间: |
|
| 查看次数: |
1386 次 |
| 最近记录: |