Friday, 18 July 2014

MS Word VSTO - Change Width and Height of Inline Shape

How do you programmatically change the Width and Height of an InlineShape in Word VSTO Application? This is a case where a user selects certain section of the Word Document and/or wants to change the width and/or the relative height of all the InlineShape objects.
  1. Your first step is to get the Selection object and eventually all the InlineShapes within the Selection.
    //Get all the selected inline shapes
    Word.Selection selection = wordApp.Selection;
    Word.InlineShapes inlineShapes = selection.InlineShapes;
    
  2. Your next step is to check whether the user have selected any InlineShapes or not. If they have selected the InlineShapes than we can loop through each one of the InlineShape.
    if (inlineShapes != null)
    {
       //Change the width & height of all selected inline shapes
       foreach (Word.InlineShape inlineShape in inlineShapes)
       {
       }
    }
    
  3. Now comes the part which we are most interested in!! Changing the Width and Height. The Width and Height properties sets the width and height of the InlineShape object's in points. An inch is equal to 72 points. So if you need to set the Width and Height to 5 Inches each, you would need to set these properties to 5 * 72 = 360 points each. But for our sake, we do not need to go into this calculations, as we have another built-int method InchesToPoints that helps us convert Inches to Points.
    float newValueInInches = 5.0F;
    float newValueInPoints = wordApp.InchesToPoints(newValueInInches);
    inlineShape.Height = newValueInPoints;
    inlineShape.Width = newValueInPoints;
    
THE COMPLETE CODE!!
//Get all the selected inline shapes
Word.Selection selection = wordApp.Selection;
Word.InlineShapes inlineShapes = selection.InlineShapes;

if (inlineShapes != null)
{
   //Set the new width in Points
   float newValueInInches = 5.0F;
   float newValueInPoints = wordApp.InchesToPoints(newValueInInches);

   //Change the width & height of all selected inline shapes
   foreach (Word.InlineShape inlineShape in inlineShapes)
   {
      inlineShape.Height = newValueInPoints;
      inlineShape.Width = newValueInPoints;
   }
}

No comments:

Post a Comment