none
c# word automation - paragraph styles and header colors (Office 2007)

    Debate general

  • Hello

    I have an application that generates a Word document. Among other things I need to repeat a three paragraphs on every page - so I use a header and it generates normally. I have two problems however:

    1. A header is by default displayed using grey font - can I change it? I'd like the paragraph to be diplayed in the same color as the rest of the document (black).

    2. I need to alternate styles between the three paragraphs, as follows:
      1st paragraph - aligned to the left
      2nd paragraph - aligned to the centre
      3rd paragraph - aligned to the left, different font size.

    I was unable to find answers to these two problems. I'd appretiate if anyone could help me in any way.

    My code is as follows. Unfortunatly, my aligning attempts align the whole header, rather than only the paragraph.

    foreach (Section sec in oWordDoc.Sections)
    {
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Name = "Arial";
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Size = 16;
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Color = WdColor.wdColorBlack;
        
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.InsertParagraphAfter();
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = "1st paragraph";
    
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.InsertParagraphAfter();
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragraphs[2].Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text += "2nd paragraph";
    
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.InsertParagraphAfter();
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragraphs[3].Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
        sec.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text += "3rd paragraph";
    }
    martes, 14 de julio de 2009 20:42

Todas las respuestas

  • Don't set the style on the text directly. It is commonly misused feature of Word, and they should not allow such a waste of formatting. Always use styles, and only in rare cases, modify the formatting of a piece of text manually.

    Anyway, here are the answers to your questions:

    1) Change the style using this code:

                object headingStyleIndex = Word.WdBuiltinStyle.wdStyleHeading1;
                Styles.get_Item(ref headingStyleIndex).Font.Color = WdColor.wdColorBlack;
    2) You can create custom styles the same way. Then, simply apply the right style. 


    Geert van Horrik - CatenaLogic
    Visit my blog: http://blog.catenalogic.com

    Looking for a way to deploy your updates to all your clients? Try Updater!
    sábado, 15 de agosto de 2009 16:07