Insert Textbox in the left margin

Hello,

I’m trying to write some text that needs to appear on every page of the document. (see doc1.docx (19.3 KB))
The text needs to appear on the page’s left margin and in the page center whether the page orientation is Portrait or Landscape. (see doc2.docx (27.0 KB))

Since the text should appear on every page of the document, I guess I should work with HeaderFooters object but I didn’t manage to get decent results.

The attachments:

  • doc1.docx is the document I get as input
  • doc2.docx is the document I want to get

I’m using the Aspose.Words for .NET (ver. 23.5)
Can anyone tell me how to get the wanted result ?

Best regards

@Irchad Your idea is absolutely right - you should use header/footer to insert content on each page. Please see the following code that produces the expected output:

Document doc = new Document(@"C:\Temp\in.docx");

// Create shape
Shape textBox = new Shape(doc, ShapeType.TextBox);
textBox.Width = 15;
textBox.Height = 200;
textBox.Stroked = false;
// Add textbox content
Paragraph content = new Paragraph(doc);
content.ParagraphFormat.Alignment = ParagraphAlignment.Center;
textBox.AppendChild(content);
content.AppendChild(new Run(doc, "This is some text on the left margin"));

// Specify textbox position.
textBox.WrapType = WrapType.None;
textBox.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
textBox.HorizontalAlignment = HorizontalAlignment.Left;
textBox.RelativeVerticalPosition = RelativeVerticalPosition.Page;
textBox.VerticalAlignment = VerticalAlignment.Center;

// Configure texbox.
textBox.TextBox.LayoutFlow = LayoutFlow.BottomToTop;
textBox.TextBox.InternalMarginTop = 0;
textBox.TextBox.InternalMarginBottom = 0;
textBox.TextBox.InternalMarginLeft = 0;
textBox.TextBox.InternalMarginRight = 0;

// insert the shape in all header types in all sections.
HeaderFooterType[] headerTypes = new HeaderFooterType[] { HeaderFooterType.HeaderPrimary, HeaderFooterType.HeaderFirst, HeaderFooterType.HeaderEven };
DocumentBuilder builder = new DocumentBuilder(doc);
foreach (Section section in doc.Sections)
{
    // Move builder to section first.
    builder.MoveTo(section.Body.FirstParagraph);

    // move to header
    foreach (HeaderFooterType headerFooterType in headerTypes)
    {
        builder.MoveToHeaderFooter(headerFooterType);
        builder.CurrentParagraph.AppendChild(textBox.Clone(true));
    }
}

doc.Save(@"C:\Temp\out.docx");

@alexey.noskov Works like a charm, thanks a lot !

1 Like