I am trying to count the number of pages that will be generated in a word document then insert the current page and total page in a bar code along with additional data, that is not relevant (test data at this point). The bar code generates successfully but the page count is off, and does something odd when it gets to page 4. The final document output is 5 pages when just saving the document WITHOUT any bar codes. below is the logic I’m using to get a bar code in each header.
private static void AddPageBreakAndSectionHeader(Document template, string headerText)
{
var runs = template.GetChildNodes(NodeType.Run, true);
var builder = new DocumentBuilder(template);
var dataStringMatches = new Regex(""(.*?)"").Matches(headerText);
var subString = “00000”;
if (dataStringMatches.Count > 0)
subString = dataStringMatches[0].Groups[1].ToString();
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
var newString = subString.Replace("{NUMPAGES}", template.PageCount.ToString()).Replace("{PAGE}", "1");
ResizeAndPositionBarcode(builder.InsertImage(CreateBarcodeImage(template, newString)));
foreach (var run in runs)
{
//Find the page number
var collector = new LayoutCollector(template);
var pageNumber = collector.GetStartPageIndex(run);
//if next run is on the next page, add a page break
var nextNode = run?.ParentNode?.NextSibling;
if (nextNode == null) continue;
var nextPageNumber = collector.GetStartPageIndex(nextNode);
if (nextPageNumber <= pageNumber) continue;
builder.MoveTo(run);
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
//Modify header footer
newString = subString.Replace("{NUMPAGES}", template.PageCount.ToString()).Replace("{PAGE}", nextPageNumber.ToString());
ResizeAndPositionBarcode(builder.InsertImage(CreateBarcodeImage(template, newString)));
}
}
I have also attached the document that is generated with the bar code on the right side.
TestMerge (2).zip (28.6 KB)