none
Different styling in a line RRS feed

  • Question

  • Hello all,

    I'm struggling with the way to give a style to the text itself or RUN in Word processing of OpenXML for WORD.

    I can see the way to style the text is  like following:

    ParagraphProperties titleProperties = new ParagraphProperties();
    titleProperties.ParagraphStyleId = new ParagraphStyleId { Val = "Title" };
    titleParagraphe.Append(titleProperties);

    But this is the way to make a style to a Paragraph but I'd like to give a style to the Text or Run instead of Paragraph. When I style the Paragraph then the next text is located in the next line. I need to apply different styles in a line like a similar way above. I prepared the styles in styles.xml and I have to apply the style from XML files.

    ie: This is an example

    Any help would be very appreciated.


    Monday, December 5, 2011 12:56 AM

Answers

  • Hi Alvin,

    I can't exactly say where is the error on your code snippet you provided. I guess there is some problems lies in the AddNewStyleFromXML method. I referred to this msdn article:

    http://msdn.microsoft.com/en-us/library/gg188064.aspx

    tried the following code on my side:

    using System.Linq;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    using DocumentFormat.OpenXml;
     
    namespace OpenXmlWordCreateAddAddCharacterStyle
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strDoc = @"CreateAndAddCharacterStyle.docx";
     
                using (WordprocessingDocument doc = WordprocessingDocument.Open(strDoc, true))
                {
                    // Get the Styles part for this document.
                    StyleDefinitionsPart part =
                        doc.MainDocumentPart.StyleDefinitionsPart;
     
                    // If the Styles part does not exist, add it.
                    if (part == null)
                    {
                        part = AddStylesPartToPackage(doc);
                    }
     
                    // Create and add the character style with the style id, style name, and
                    // aliases specified.
                    CreateAndAddCharacterStyle(part,
                        "OverdueAmountChar",
                        "Overdue Amount Char",
                        "Late Due, Late Amount");
     
                    // Add a paragraph with a run with some text.
                    Paragraph p =
                        new Paragraph(
                            new Run(
                                new Text("this is some text ") { Space = SpaceProcessingModeValues.Preserve }));
     
                    // Add another run with some text.
                    p.AppendChild<Run>(new Run(new Text("in a run ") { Space = SpaceProcessingModeValues.Preserve }));
     
                    // Add another run with some text.
                    p.AppendChild<Run>(new Run(new Text("in a paragraph.") { Space = SpaceProcessingModeValues.Preserve }));
     
                    // Add the paragraph as a child element of the w:body.
                    doc.MainDocumentPart.Document.Body.AppendChild(p);
     
                    // Get a reference to the second run (indexed starting with 0).
                    Run r = p.Descendants<Run>().ElementAtOrDefault(1);
     
                    // If the Run has no RunProperties object, create one.
                    if (r.Elements<RunProperties>().Count() == 0)
                    {
                        r.PrependChild<RunProperties>(new RunProperties());
                    }
     
                    // Get a reference to the RunProperties.
                    RunProperties rPr = r.RunProperties;
     
                    // Set the character style of the run.
                    if (rPr.RunStyle == null)
                        rPr.RunStyle = new RunStyle();
                    rPr.RunStyle.Val = "OverdueAmountChar";
                }
            }
     
            private static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart,
        string styleid, string stylename, string aliases = "")
            {
                // Get access to the root element of the styles part.
                Styles styles = styleDefinitionsPart.Styles;
     
                // Create a new character style and specify some of the attributes.
                Style style = new Style()
                {
                    Type = StyleValues.Character,
                    StyleId = styleid,
                    CustomStyle = true
                };
     
                // Create and add the child elements (properties of the style).
                Aliases aliases1 = new Aliases() { Val = aliases };
                StyleName styleName1 = new StyleName() { Val = stylename };
                LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" };
                if (aliases != "")
                    style.Append(aliases1);
                style.Append(styleName1);
                style.Append(linkedStyle1);
     
                // Create the StyleRunProperties object and specify some of the run properties.
                StyleRunProperties styleRunProperties1 = new StyleRunProperties();
                Bold bold1 = new Bold();
                Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
                RunFonts font1 = new RunFonts() { Ascii = "Tahoma" };
                Italic italic1 = new Italic();
                // Specify a 24 point size.
                FontSize fontSize1 = new FontSize() { Val = "48" };
                styleRunProperties1.Append(font1);
                styleRunProperties1.Append(fontSize1);
                styleRunProperties1.Append(color1);
                styleRunProperties1.Append(bold1);
                styleRunProperties1.Append(italic1);
     
                // Add the run properties to the style.
                style.Append(styleRunProperties1);
     
                // Add the style to the styles part.
                styles.Append(style);
            }
     
            private static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc)
            {
                StyleDefinitionsPart part;
                part = doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
                Styles root = new Styles();
                root.Save(part);
                return part;
            }
        }
    }
    

    It works well. You can make use of the sample code and see whether you can get some hints about the problem.
    If you still can't find the problem, you'd better upload your project to the skydrive: http://www.skydrive.com and share with us so that we can better analyze your problem and find the workaround. Wish you a nice day.

    Best Regards,


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    • Marked as answer by Bruce Song Tuesday, December 20, 2011 2:56 AM
    Friday, December 9, 2011 10:48 AM

All replies

  • Hi Alvin KY,

    Thank you for posting.

    It is possible to apply the style to the text by setting the RunProperties. For example:


            // Creates an Run instance and adds its children.
            public Run GenerateRun()
            {
                Run run1 = new Run(){ RsidRunProperties = "009531B2" };

                RunProperties runProperties1 = new RunProperties();
                RunStyle runStyle1 = new RunStyle(){ Val = "Heading2Char" };

                runProperties1.Append(runStyle1);
                Text text1 = new Text();
                text1.Text = "This";

                run1.Append(runProperties1);
                run1.Append(text1);
                return run1;
            }

    Hope this can give you some hint and just feel free to follow up after you have tried.

    Best Regards,


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    Tuesday, December 6, 2011 7:50 AM
  • Much appreciate. But in my case, it doesn't work. I can guess there is no problem in your code but problem from my code. I am not used to OpenXML.

    private int _gIndex = 100000;

    protected void btn6_Click(object sender, EventArgs e)
            {
                _gFileName = "Cas_" + _gIndex.ToString();
                OpenNewCASTemplate();
                AddNewStyleFromXML();

                Paragraph _para = new Paragraph();
                _para.Append(AddStyle("This is a test", "casHeadingLarge"));
                _gMainDocPart.Document.Append(_para);

                // Save & Close the document
                _gMainDocPart.Document.Save();
                _gXMLWordDoc.Close();
                _gXMLWordDoc.Dispose();
                // set the document as Read-Only
            }

     

    private void OpenNewCASTemplate()
            {
                File.Copy(Server.MapPath(@"DocumentCache/CAS_Template.docx"),
                            Server.MapPath(@"DocumentCache/" + _gFileName + ".docx"),
                            true);

                _gXMLWordDoc = WordprocessingDocument.Open(Server.MapPath(@"DocumentCache/" + _gFileName + ".docx"), true);
                _gMainDocPart = _gXMLWordDoc.MainDocumentPart;

                _gStyleDefPart = _gMainDocPart.StyleDefinitionsPart;
                /*
                 * FileStream stylesTemplate = new FileStream(Server.MapPath(@"XML/styles.xml"), FileMode.Open, FileAccess.Read);
                _gStyleDefPart.FeedData(stylesTemplate);
                // _gStyleDefPart.AddPart(stylesTemplate);
                _gStyleDefPart.Styles.Save();
                 * */
            }

     

    private void AddNewStyleFromXML()
            {

    /* Add style into Style.xml and found no problem in XML. */
    .......

              _gStyleDefPart.Styles.Save();
            }

    private Run AddStyle(string _text, string _styleName, string _fontName = "Arial")
            {
                Run _run = new Run();
                RunProperties _runProp = new RunProperties();

                RunStyle _style1 = new RunStyle() { Val = _styleName };
                _runProp.Append(_style1);

                Text _txt = new Text(_text);
                _run.Append(_runProp);
                _run.Append(_txt);
                return _run;
            }

     

    Document is successfully generated but style is not applied. I reckon there is some misunderstanding on the step to handle the WORD with OpenXML.

    Would be very appreciated for your any comment and help.


    Alvin
    Tuesday, December 6, 2011 10:15 PM
  • Hi Alvin,

    I can't exactly say where is the error on your code snippet you provided. I guess there is some problems lies in the AddNewStyleFromXML method. I referred to this msdn article:

    http://msdn.microsoft.com/en-us/library/gg188064.aspx

    tried the following code on my side:

    using System.Linq;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    using DocumentFormat.OpenXml;
     
    namespace OpenXmlWordCreateAddAddCharacterStyle
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strDoc = @"CreateAndAddCharacterStyle.docx";
     
                using (WordprocessingDocument doc = WordprocessingDocument.Open(strDoc, true))
                {
                    // Get the Styles part for this document.
                    StyleDefinitionsPart part =
                        doc.MainDocumentPart.StyleDefinitionsPart;
     
                    // If the Styles part does not exist, add it.
                    if (part == null)
                    {
                        part = AddStylesPartToPackage(doc);
                    }
     
                    // Create and add the character style with the style id, style name, and
                    // aliases specified.
                    CreateAndAddCharacterStyle(part,
                        "OverdueAmountChar",
                        "Overdue Amount Char",
                        "Late Due, Late Amount");
     
                    // Add a paragraph with a run with some text.
                    Paragraph p =
                        new Paragraph(
                            new Run(
                                new Text("this is some text ") { Space = SpaceProcessingModeValues.Preserve }));
     
                    // Add another run with some text.
                    p.AppendChild<Run>(new Run(new Text("in a run ") { Space = SpaceProcessingModeValues.Preserve }));
     
                    // Add another run with some text.
                    p.AppendChild<Run>(new Run(new Text("in a paragraph.") { Space = SpaceProcessingModeValues.Preserve }));
     
                    // Add the paragraph as a child element of the w:body.
                    doc.MainDocumentPart.Document.Body.AppendChild(p);
     
                    // Get a reference to the second run (indexed starting with 0).
                    Run r = p.Descendants<Run>().ElementAtOrDefault(1);
     
                    // If the Run has no RunProperties object, create one.
                    if (r.Elements<RunProperties>().Count() == 0)
                    {
                        r.PrependChild<RunProperties>(new RunProperties());
                    }
     
                    // Get a reference to the RunProperties.
                    RunProperties rPr = r.RunProperties;
     
                    // Set the character style of the run.
                    if (rPr.RunStyle == null)
                        rPr.RunStyle = new RunStyle();
                    rPr.RunStyle.Val = "OverdueAmountChar";
                }
            }
     
            private static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart,
        string styleid, string stylename, string aliases = "")
            {
                // Get access to the root element of the styles part.
                Styles styles = styleDefinitionsPart.Styles;
     
                // Create a new character style and specify some of the attributes.
                Style style = new Style()
                {
                    Type = StyleValues.Character,
                    StyleId = styleid,
                    CustomStyle = true
                };
     
                // Create and add the child elements (properties of the style).
                Aliases aliases1 = new Aliases() { Val = aliases };
                StyleName styleName1 = new StyleName() { Val = stylename };
                LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" };
                if (aliases != "")
                    style.Append(aliases1);
                style.Append(styleName1);
                style.Append(linkedStyle1);
     
                // Create the StyleRunProperties object and specify some of the run properties.
                StyleRunProperties styleRunProperties1 = new StyleRunProperties();
                Bold bold1 = new Bold();
                Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 };
                RunFonts font1 = new RunFonts() { Ascii = "Tahoma" };
                Italic italic1 = new Italic();
                // Specify a 24 point size.
                FontSize fontSize1 = new FontSize() { Val = "48" };
                styleRunProperties1.Append(font1);
                styleRunProperties1.Append(fontSize1);
                styleRunProperties1.Append(color1);
                styleRunProperties1.Append(bold1);
                styleRunProperties1.Append(italic1);
     
                // Add the run properties to the style.
                style.Append(styleRunProperties1);
     
                // Add the style to the styles part.
                styles.Append(style);
            }
     
            private static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc)
            {
                StyleDefinitionsPart part;
                part = doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
                Styles root = new Styles();
                root.Save(part);
                return part;
            }
        }
    }
    

    It works well. You can make use of the sample code and see whether you can get some hints about the problem.
    If you still can't find the problem, you'd better upload your project to the skydrive: http://www.skydrive.com and share with us so that we can better analyze your problem and find the workaround. Wish you a nice day.

    Best Regards,


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    • Marked as answer by Bruce Song Tuesday, December 20, 2011 2:56 AM
    Friday, December 9, 2011 10:48 AM