Search code examples
c#itextmvcrazortopdf

Display page numbers with MvcRazorToPdf


I am trying to use this package in a project of mine and would like to display the page number. There is a property on the Document object that has the PageNumber but. I have no clue how to access it from the view

Current code:

PrintManager prntManager = new PrintManager();
var data = prntManager.ObjectToPdf(item, para);
byte[] pdf = null;

pdf = ControllerContext.GeneratePdf(prntManager.CreateController<PrintingController>(), data, prntManager.ReportToView(para.Export.Report.Code));   

HttpContext.Current.Response.AppendHeader("Export-Location", prntManager.GeneratePdf(pdf));

Solution

  • If someone has the same problem here is my solution:

    PrintManager prntManager = new PrintManager();
    var data = prntManager.ObjectToPdf(item, para);
    byte[] pdf = null;
    var cfg = new Action<iTextSharp.text.pdf.PdfWriter,iTextSharp.text.Document>((writer, document) =>
    {
        writer.PageEvent = new StandardPrintHelper();
        document.NewPage();
    });
    
    pdf = ControllerContext.GeneratePdf(prntManager.CreateController<PrintingController>(), data, prntManager.ReportToView(para.Export.Report.Code), cfg);   
    
    HttpContext.Current.Response.AppendHeader("Export-Location",
        prntManager.GeneratePdf(pdf));
    

    StandardPrintHelper:

    public class StandardPrintHelper : iTextSharp.text.pdf.PdfPageEventHelper
    {
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(writer.PageNumber.ToString()), 500, 140, 0);
        }
    }