Get total number of pages going to be printed to pdf

Hello,

I would like to get the number of pages that are going to be printed from excel to pdf (ex 5 pages) in order to add this number on the first page. ex. “Document is printed on 5 pages”.

I know how to add the current page (ex 1/5) on the header or footer, but I also would need to somehow get the total number in the code before the document is printed to pdf. Any ideas?

Thanks in advance!
Gabriel

Hi Gabriel,

You could add this text in the first page’s header, like this:

var workbook = ExcelFile.Load("input.xlsx");
var worksheet = workbook.Worksheets.ActiveWorksheet;

worksheet.HeadersFooters.FirstPage.Header.LeftSection
    .Append("Document is printed on ")
    .Append(HeaderFooterFieldType.NumberOfPages)
    .Append(" pages.");

workbook.Save("output.pdf");

Or if you still want to place that text into some cell, then you could do this:

var workbook = ExcelFile.Load("input.xlsx");
var worksheet = workbook.Worksheets.ActiveWorksheet;

// I'm adding an empty row to make space for that sentence in the "A1" cell.
worksheet.Rows.InsertEmpty(0);

int pagesCount = workbook.GetPaginator().Pages.Count;
worksheet.Cells["A1"].Value = $"Document is printed on {pagesCount} pages.";

workbook.Save("output.pdf");

Does this solve your issue?

Regards,
Mario

Yes, looks like this was the case, it seems like in some situations the GetPaginator() function returns null.

When creating a new empty workbook for example with var workbook = new ExcelFile().

Any idea about this behavior?

Hi,

Yes, you don’t have any sheets.

Regards,
Mario