0

How can I do loop by pages? I need to set some element to top and bottom for all pages without using header, footer and watermark. I use code bellow, but it doesn't work for all documents.

public void AddLabel()
{
   IEnumerable<Paragraph> topP = wdDoc.MainDocumentPart.Document.Body.Elements<Paragraph>();
   bool skip = false;
   foreach (Paragraph p in topP)
   {
      if (!ContainLastRenderedPageBreak(p))
      {
         if (!skip)
         {
           p.Append(runElementFooter.CloneNode(true));
           p.Append(runElementHeader.CloneNode(true));
           skip = true;
         }
       }
       else skip = false;
       if (ContainPageBreak(p))
       {
         p.Append(runElementFooter.CloneNode(true));
         p.Append(runElementHeader.CloneNode(true)); 
         skip = false; 
       }
   }
}
public bool ContainPageBreak(Paragraph p)
{
 return p.Elements<Run>().FirstOrDefault(r => r.Elements<Break>().FirstOrDefault(b => b.Type == BreakValues.Page) != null) != null;
}
public bool ContainLastRenderedPageBreak(Paragraph p)
{
 return p.Elements<Run>().FirstOrDefault(r => r.Elements<LastRenderedPageBreak>().FirstOrDefault() != null) != null;
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
Alexey
  • 11
  • 2

1 Answers1

0

Something like that (ie relying on LastRenderedPageBreak) is the best you'll do, short of building a page layout model (easy enough if your pages only contain paragraphs of text; harder in the more general case).

JasonPlutext
  • 15,352
  • 4
  • 44
  • 84