Niels Ziegler
Niels Ziegler

Reputation: 456

Insert a textbox on a specific word page

I am iterating through all storyranges in a word document, to find shapes that do not adhere to company standards. When I find such a shape, I would like to add a textbox in the upper right corner of it's page. I only managed to add it to the first page so far.

foreach (Word.InlineShape shape in storyRange.InlineShapes)
        {
            if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture)
            {
                if (shape.Width != CurrentWordApp.CentimetersToPoints(Constants.LogoWidth))
                {
                    anchor = shape.Range;
                    shapePageNumber = (int)shape.Range.Information[Word.WdInformation.wdActiveEndPageNumber];
                    AddMarkerToPage(shapePageNumber, anchor);
                }
            }
        }     

This is an excerpt from the AddMarkerToPage method. The only place I found to add a textbox, is the header. And the only place I found the header was through the section object. But section does not equal page.

 Word.HeaderFooter header =  anchor.Sections.First.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
 if (!pageHasMarker)
        {
            Word.Shape tbx = header.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromLeft),
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromTop),
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerWidth),
                         CurrentWordApp.CentimetersToPoints(Helper.errorMarkerHeight), pageRange);
            tbx.Name = "errorBox";
            tbx.TextFrame.TextRange.Text = Resources.Strings.txtDesignCheckHeaderLogo;
        }
 }

How can I either get to the header on the page the shape is on, or have another object that allows me to position a textbox on a specific page (I have the number available from the shape object)

Upvotes: 0

Views: 1230

Answers (1)

Chris
Chris

Reputation: 3519

Don't use the header, use the Document.Shapes collection.

Word.Shape tbx = <document>.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromLeft),
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromTop),
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerWidth),
                  CurrentWordApp.CentimetersToPoints(Helper.errorMarkerHeight), anchor);
tbx.Name = "errorBox";
tbx.TextFrame.TextRange.Text = Resources.Strings.txtDesignCheckHeaderLogo;

I think you'll also need these:

tbx.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
tbx.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionColumn;

Upvotes: 1

Related Questions