Displaying headers and footers in a PDF generated by Rotativa
I've found a documentation of wkhtmltopdf (or a better archived version) and it is described there how to manage headers and footers.
Basically you can just add --header-center "text"
(or similar switches) to the argument list and that's all.
So using it with Rotativa it would be:
public ActionResult ShowPdf()
{
var model = new Model();
return new ViewAsPdf("view.cshtml", model)
{
FileName = "Report.pdf",
CustomSwitches = "--print-media-type --header-center \"text\""
};
}
(I don't know if --print-media-type
is necessary.)
If you wanted to display a View instead of text in the header/footer then you can do so like this:
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();
}
Don't forget to add the [AllowAnonymous] attribute on the Footer action otherwise Rotatina can't get access to the path.
Here is how I did it (in full):
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 });
}