在Rotativa生成的PDF中显示页眉和页脚
本文关键字:显示 PDF Rotativa | 更新日期: 2023-09-27 18:02:29
我试图在Rotativa库生成的PDF中指定页眉和页脚。正如作者在这里回答的那样,使用CSS(在这里描述)应该是可能的。但是,我不能这样做。
我在meta标签中加载了一个样式表:
<link href="print.css" rel="stylesheet" type="text/css" media="print" />
在底部的样式表中:
@page {
@top-left {
content: "TOP SECRET";
color: red
}
@bottom-right {
content: counter(page);
font-style: italic
}
}
然后生成PDF:
public ActionResult ShowPdf()
{
var model = new Model();
return new ViewAsPdf("view.cshtml", model)
{
FileName = "Report.pdf",
CustomSwitches = "--print-media-type"
};
}
然后PDF的页眉和页脚什么也没有出现。什么好主意吗?
我找到了wkhtmltopdf(或更好的存档版本)的文档,其中描述了如何管理页眉和页脚。
基本上你可以把--header-center "text"
(或类似的开关)添加到参数列表中,这就是全部。
那么在Rotativa中使用它就是:
public ActionResult ShowPdf()
{
var model = new Model();
return new ViewAsPdf("view.cshtml", model)
{
FileName = "Report.pdf",
CustomSwitches = "--print-media-type --header-center '"text'""
};
}
(我不知道--print-media-type
是否必要)
如果你想在页眉/页脚显示视图而不是文本,那么你可以这样做:
public ActionResult ViewPDF()
{
string customSwitches = string.Format("--print-media-type --allow {0} --footer-html {0} --footer-spacing -10",
Url.Action("Footer", "Document", new { area = ""}, "https"));
return new ViewAsPdf("MyPDF.cshtml", model)
{
FileName = "MyPDF.pdf",
CustomSwitches = customSwitches
};
}
[AllowAnonymous]
public ActionResult Footer()
{
return View();
}
不要忘记在Footer动作上添加[AllowAnonymous]属性,否则Rotatina无法访问路径
我是这样做的(全文):
public ActionResult PrintPDF(int? selectedSiteRotaId, int selectedSiteId)
{
string footer = "--footer-center '"Printed on: " + DateTime.Now.Date.ToString("MM/dd/yyyy") + " Page: [page]/[toPage]'"" + " --footer-line --footer-font-size '"9'" --footer-spacing 6 --footer-font-name '"calibri light'"";
return new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
{
FileName = "PDF_Output.pdf",
PageOrientation = Orientation.Landscape,
MinimumFontSize = 10,
//PageMargins = new Margins(5,5,5,5),
PageSize = Size.A3,
CustomSwitches = footer
};
//var pdfResult = new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
//{
// FileName = "PDF_Output.pdf",
// PageOrientation = Orientation.Landscape,
// MinimumFontSize = 10
//};
//var binary = pdfResult.BuildPdf(this.ControllerContext);
//return File(binary, "application/pdf");
}
public ActionResult RenderPDF(int? selectedSiteRotaId, int selectedSiteId)
{
return RedirectToAction("Index", "PrintPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 });
}
string customSwitches = string.Format("--header-spacing '"0'" --footer-spacing '"0'" --footer-html {0} ", Url.Action("Footer", "Invoice", new { }, "http"));
return new ViewAsPdf(saleInvoiceVm)
{
PageOrientation = Orientation.Portrait,
PageSize = Rotativa.AspNetCore.Options.Size.A4,
PageMargins = { Left = 5, Bottom = 25, Right = 7, Top = 10 },
CustomSwitches = customSwitches,
};
试一下,它会100%工作
return new ViewAsPdf("MyPDF.cshtml", model)
{
FileName = "MyPDF.pdf",
CustomSwitches = customSwitches
};
}