Hi Jak,
Thanks
for your inquiry. There is one extra line of code in my previous post and I have removed that line. In your case, the PageSetup.TopMargin return correct value. However, in your document, the header’s content flow down to the page which increase the header’s height more then the value of TopMargin.
In this case, I suggest you please get the position of first paragraph of section’s body using LayoutEnumerator.Rectangle. This property returns the bounding rectangle of the current entity relative to the page top left corner (in points). Please use the following code example to achieve your requirements.
Hope this helps you. Please let us know if you have any more queries.
Document _document = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(_document);
int sectionIndex;
sectionIndex = 0;
LayoutCollector layoutCollector = new LayoutCollector(_document);
LayoutEnumerator layoutEnumerator = new LayoutEnumerator(_document);
foreach (Section section in _document.Sections)
{
var renderObject = layoutCollector.GetEntity(section.Body.FirstParagraph);
layoutEnumerator.Current = renderObject;
RectangleF location = layoutEnumerator.Rectangle;
var width = section.PageSetup.PageWidth;
var headerHeight = location.Y;
builder.MoveToSection(sectionIndex);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape headerbox = new Shape(_document, ShapeType.TextBox);
headerbox.Name = "TestBox";
headerbox.Width = width;
headerbox.Height = headerHeight;
headerbox.RelativeVerticalPosition = RelativeVerticalPosition.Page;
headerbox.VerticalAlignment = VerticalAlignment.Top;
headerbox.HorizontalAlignment = HorizontalAlignment.Center;
headerbox.WrapType = WrapType.None;
headerbox.BehindText = false;
headerbox.FillColor = System.Drawing.Color.White;
headerbox.Filled = true;
headerbox.Stroked = false;
headerbox.Top = -section.PageSetup.HeaderDistance;
Paragraph headerParagraph = new Paragraph(_document);
headerParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Center;
headerbox.AppendChild(headerParagraph);
Run headerText = new Run(_document, "TEST CONTENT");
headerText.Font.Size = 20;
headerText.Font.Color = System.Drawing.Color.Red;
headerText.Font.Name = "Arial";
headerParagraph.AppendChild(headerText);
builder.InsertNode(headerbox);
sectionIndex++;
}
_document.Save(MyDir + "Out.docx");