Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make shape stay always on first page

Tags:

c#

ms-word

vsto

I am developing VSTO application add-in for Word and want to make shape be always on first page on fixed position. Is there a way to do this without actively monitoring state of a shape?

Answers that state "it can't be done" with good why explanation, are also welcome.

like image 624
Logman Avatar asked May 11 '17 15:05

Logman


2 Answers

If you put your shape to header and check DifferentFirstPageHeaderFooter, page break do not have effect as you need, but the shape will be on background and Page Layout > Breaks > Next Page duplicate the shape to the next page.

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        AddFixedShapeOnFistPage(Application.Documents.Add(System.Type.Missing), MsoAutoShapeType.msoShapeRectangle, 160, 160, 30, 30);
    }

    public void AddFixedShapeOnFistPage(Microsoft.Office.Interop.Word.Document wordDocument, Microsoft.Office.Core.MsoAutoShapeType shapeType,int left, int top, int width, int height)
    {
        int wordTrueConst = -1; //https://social.msdn.microsoft.com/Forums/office/en-US/e9f963a9-18e4-459a-a588-17824bd3906d/differentfirstpageheaderfooter-bool-or-int?forum=worddev
        wordDocument.Sections[1].PageSetup.DifferentFirstPageHeaderFooter = wordTrueConst;
        wordDocument.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Shapes.AddShape((int)shapeType, left, top, width, height);
    }

Shape will be on background

like image 96
Denis P. Avatar answered Oct 09 '22 02:10

Denis P.


Yes, it is achievable. The code as follows:

using Word = Microsoft.Office.Interop.Word;

public void DrawShape()
{
try{
    var wordApp = new Word.Application();
    wordApp.Documents.Add(System.Type.Missing);
    Word.Document doc = wordApp.ActiveDocument;
    var shape = doc.Shapes.AddShape((int)Microsoft.Office.Core.MsoAutoShapeType.msoShapeRectangle, 20, 20, 60, 20);
   }
   catch(Exception ex) { }
}

The aforementioned code draws a rectangle of width: 60, height: 20 at position (20, 20) in the top left corner position of the document's first page. Keep in mind, (0,0) is the beginning point from the top left corner of the first page of the Doc file.

Here, Shapes.AddShape should do the trick.

Shape AddShape(int Type, float Left, float Top, float Width, float Height, ref object Anchor = Type.Missing);

More on SHapes.AddShape(): https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.shapes.addshape.aspx

And for different types of shapes refer to MsoAutoShapeType: https://msdn.microsoft.com/en-us/library/microsoft.office.core.msoautoshapetype.aspx

like image 28
Somdip Dey Avatar answered Oct 09 '22 03:10

Somdip Dey