DomMa
DomMa

Reputation: 151

c# How to get standard font style object in Word

I'm inserting variable text from a *.html file into a Word document and have to adapt the font(name and size) of the inserted text to the rest of the document. I have a working solution but I don't like the way I did it, so I'm searching another way to get the standard font name and size from Word application. Another problem is that NameLocal can be in different languages. So I also need another way to find the Headers. I already tried Style.Type but it has always value "1" My code so far:

foreach (Word.Style style in Globals.ThisAddIn.Application.ActiveDocument.Styles)
  {
    if (style.NameLocal.Equals("Normal")) // find correct style object
    {
      float size = style.Font.Size;
      string font = style.Font.Name;

      foreach (Word.Paragraph paragraph in Globals.ThisAddIn.Application.ActiveDocument.Paragraphs)
      {
        if (paragraph.Range.get_Style().NameLocal.Contains("Heading")) // find all headers
        {
          paragraph.Range.Font.Size = size;
          paragraph.Range.Font.Name = font;
        }
      }
      break;
    }
  }

The reason why I'm not simply changing the style is so the headers are still marked as headers. I'm pretty clueless atm

Upvotes: 2

Views: 1789

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

For built-in styles, the Word object model provides the enumeration WdBuiltinStyle. Using this instead of a string value (the local name of a style) makes specifying a style language-independent. In addition, the built-in styles will always be present in a document so there's no need to loop the Styles collection of a document to get a particular style.

So, for example:

Word.Document doc = Globals.ThisAddin.Application.ActiveDocument;
Word.Style style = doc.Styles[Word.WdBuildinStyle.wdStyleNormal];
float size = style.Size;
string font = style.Font.Name;
foreach (Word.Paragraph paragraph in doc)
{
    if (paragraph.Range.get_Style() = Word.WdBuildinStyle.wdStyleHeading1)
    {
     paragraph.Range.Font.Size = size;
     paragraph.Range.Font.Name = font;
     }
}

Upvotes: 1

Related Questions