我正在尝试在Rotativa库生成的PDF中指定页眉和页脚。正如作者回答here,应该可以使用CSS(描述here)。但是,我无法做到这一点。
我在元标记中加载了样式表:
<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的页眉和页脚中没有任何内容。有什么想法吗?
答案 0 :(得分:9)
我找到了documentation of 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
。)
答案 1 :(得分:6)
如果你想在页眉/页脚中显示一个View而不是文本,那么你可以这样做:
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();
}
不要忘记在页脚操作上添加[AllowAnonymous]属性,否则Rotatina无法访问该路径。
答案 2 :(得分:4)
我是这样做的(完整的):
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 });
}
答案 3 :(得分:-1)
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,
};