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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With