We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

How to determine current page count during mail merge


I am dealing with mail merge templates that have freetext fields that can take any amount of text which may cause the document to dynamically expand to any number of pages per mail merge record.

I tried hooking into the FieldMerginCallback and querying e.getDocument().getPageCount(), but this count does not seem to get updated with the actual number of pages during the mail merge.

And there seems to be no other callback that gets executed per record or per page added. Am I missing something? This seems fairly straight forward and in my case is needed so I can generate appropriate barcodes for each individual page of the mailmerge as well as for reporting and billing purposes.


I found a hacky solution but it seems to work.

  1. add PAGE field to HEADER_PRIMARY
  2. mailmerge
  3. run doc.accept() with visitRun which then parses the text and then removes the field.

I have yet to test if this breaks for different templates or scenarios, but so far so good. A proper built-in callback in/after mailmerge or during save would certainly be preferable.

Hi Daniel,

Thanks for your inquiry. In your case, we suggest you please use LayoutCollector.GetStartPageIndex method to get total pages of document as shown below. Hope this helps you.

public void fieldMerging(FieldMergingArgs args) throws Exception {
    // Your code...
    // Your code...
    LayoutCollector collector = new LayoutCollector(args.getDocument());
    int pagecount = collector.getStartPageIndex(args.getDocument().getLastSection().getBody().getLastParagraph());

Thanks Tahir,

Unfortunanely this doesn’t quite seem to calculate the numbers correctly. I also tried getEndPageIndex. It might work for the first record, but subsequent ones are off. I will do more testing and clean up my code so I provide a repeatable example.

This method also significantly slows down the mail merge. My approach is roughly twice as fast.


Hi Daniel,

Thanks for your inquiry. Yes, LayoutCollector approach is slower than the approach which you used. The LayoutCollector.GetStartPageIndex method builds page layout for each record during mail merge.

In your approach we suggest you please call Paragraph.Accept method instead of Document.Accept. Call Paragraph.Accept method for the paragraph which contains the NUMPAGES field.

Please let us know if you have any more queries.