Search code examples
ms-wordvstooffice-interopoffice-addins

How to add a "side" header or footer and align it vertically with word add-in vsto using c#?


I would like to insert a header OR footer and align it vertically to the side of the page using word addin vsto via C#. The following is a sample end result I would like to see. I've tried to research this and could not find an example of some one doing this PROGRAMMATICALLY? Does anyone know how to achieve this?

enter image description here

So right now I am inserting a textbox and I can align it to the side of the page like so but I don't want my end user to be able to select or delete it. So i'm thinking the solution would be to put it in a "side" header or footer... but now the problem is how do I achieve the same alignment and positioning?


Solution

  • So answering my own question. You can obtain the "header" from the current active document and the header even though it appears to be only at the top it actually spans the entire document which can hold anything (think of layers in adobe photo shop). Anyways, so to insert into this header layer and align vertically a textbox can be achieved with the following:

    //note: we are in ThisAddin.cs (word addin) and this.Application = word addin
    
    private void drawTdCycleTextBox(String cycleCode)
            {
                int length = 1000;
    
                // get the current cursor location
                Range cursorRange = this.Application.Selection.Range;
    
                // get the primary header on the current page
                HeaderFooter header = this.Application.ActiveDocument.Sections.First.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
                // header.Range.Text = "THIS IS A TEST";
    
                // create the textbox inside the header and at the current cursor location
                Microsoft.Office.Interop.Word.Shape textBox = header.Shapes.AddTextbox(Office.MsoTextOrientation.msoTextOrientationUpward, 0, 0, 35, length, cursorRange);
                textBox.TextFrame.TextRange.Font.Size = 20;
                textBox.TextFrame.TextRange.Text = Util.repeatedTextOutput(cycleCode, 25, length);
                textBox.Fill.ForeColor.RGB = ColorTranslator.ToOle(Color.Turquoise);
                textBox.Fill.Transparency = .35F;
            }