0
votes

I am copy all the content from OpenXml word file to another OpenXml word file. But during the copy I want to make some changes depending on the style. for Examlpe if the text inside of some paragraph is red I will change it to blue.

How to I get the style of specific Run of paragraph?

I use this code to foreach all the paragraphs and copy to other file:

byte[] docByteArray = File.ReadAllBytes(HttpContext.Current.Server.MapPath("\\")
    + "\\from.docx");
using (MemoryStream memoryStream = new MemoryStream())
{
    memoryStream.Write(docByteArray, 0, docByteArray.Length);
    using (WordprocessingDocument doc =
    WordprocessingDocument.Open(memoryStream, true))
    {
        RevisionAccepter.AcceptRevisions(doc);
        XElement root = doc.MainDocumentPart.GetXDocument().Root;
        XElement body = root.LogicalChildrenContent().First();
        foreach (XElement blockLevelContentElement in body.LogicalChildrenContent())
        {
            if (blockLevelContentElement.Name == W.p)
            {
                var text = blockLevelContentElement
                    .LogicalChildrenContent()
                    .Where(e => e.Name == W.r)
                    .LogicalChildrenContent()
                    .Where(e => e.Name == W.t)
                    .Select(t => (string)t)
                    .StringConcatenate();

                //addToOtherDocCode().....
            }
        }
    }
}

So when I determine that the element is paragraph I can to loop all the run inside but how can I get its style (color, bold, italic, size...)?

1

1 Answers

1
votes

Style is inside of the ParagaphProperties element w:color is color, w:b indicates bold, ect.

https://msdn.microsoft.com/EN-US/library/office/documentformat.openxml.wordprocessing.paragraphproperties.aspx

The following gets the xml for the paragaph properties and text for that paragaph, hope this helps!

byte[] docByteArray = File.ReadAllBytes("testDoc.docx");
using (MemoryStream memoryStream = new MemoryStream())
{
    memoryStream.Write(docByteArray, 0, docByteArray.Length);
    using (WordprocessingDocument doc =
    WordprocessingDocument.Open(memoryStream, true))
    {
        var body = doc.MainDocumentPart.Document.Body;
        var paragraphs = new List<Paragraph>();

        foreach(Paragraph paragraph in body.Descendants<Paragraph>()
            .Where(e => e.ParagraphProperties != null))
        {
            if(paragraph.ParagraphProperties.ParagraphMarkRunProperties != null)
            {
                foreach(OpenXmlElement element in paragraph.ParagraphProperties.ParagraphMarkRunProperties.ChildElements)
                {
                    Console.WriteLine(element.OuterXml);
                }
            }

            Console.WriteLine(paragraph.InnerText);
            }
        }
    }
}