Blue Eyed Behemoth
Blue Eyed Behemoth

Reputation: 3872

Adding multiple images to a word document at a specific locations OpenXML

I am using Office Open XML and I have to add images at a specific points. On the document I have a 'tag' so I can locate it just fine. However, when I add more than one image, it corrupts the file.

enter image description here

Here's my code: (Modified from https://msdn.microsoft.com/en-us/library/office/bb497430.aspx)

Using:

using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;

My Main:

private const string Loc = @"D:\Documents\2-Mass Output.docx";
static void Main(string[] args)
{
    var images = new[]
    {
        @"D:\Documents\NPL.bmp",
        @"D:\Documents\NVT.bmp",
        @"D:\Documents\MPL.bmp",
        @"D:\Documents\MVT.bmp"
    };
    var tags = new[]
    {
        "NormalGraph1",
        "NormalGraph2",
        "MisGraph1",
        "MisGraph2"
    };

    InsertPicture(Loc, images, tags);
}

Here are the methods:

/// <summary>
/// Inserts a picture in a paragraph with a specific text
/// </summary>
/// <param name="document">Where the file is located</param>
/// <param name="fileName">Name of the image file</param>
/// <param name="tag">Insert Image in the first paragraph that contains this text</param>
public static void InsertPicture(string document, string[] fileName, string[] tag)
{
    using (var wordprocessingDocument = WordprocessingDocument.Open(document, true))
    {
        var mainPart = wordprocessingDocument.MainDocumentPart;

        for (var i = 0; i < fileName.Length; i++)
        {
            var imagePart = mainPart.AddImagePart(ImagePartType.Bmp);
            using (var stream = new FileStream(fileName[i], FileMode.Open))
            {
                imagePart.FeedData(stream);
            }
            AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), tag[i]);
        }
    }
}

private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, string tag)
{
    // Define the reference of the image.
    var element =
            new Drawing(
                new DW.Inline(
                    new DW.Extent { Cx = 5d.Inches(), Cy = 2.66.Inches() }, // Width and Height of the image in inches. 1" = 1000000L
                    new DW.EffectExtent
                    {
                        LeftEdge = 0L,
                        TopEdge = 0L,
                        RightEdge = 0L,
                        BottomEdge = 0L
                    },
                    new DW.DocProperties
                    {
                        Id = 1U,
                        Name = tag // Make sure all of the images have a different name
                    },
                    new DW.NonVisualGraphicFrameDrawingProperties(
                        new A.GraphicFrameLocks { NoChangeAspect = true }),
                    new A.Graphic(
                        new A.GraphicData(
                            new PIC.Picture(
                                new PIC.NonVisualPictureProperties(
                                    new PIC.NonVisualDrawingProperties
                                    {
                                        Id = (UInt32Value)0U,
                                        Name = $"{tag}.bmp" // Make sure all of the images have a different name
                                    },
                                    new PIC.NonVisualPictureDrawingProperties()),
                                new PIC.BlipFill(
                                    new A.Blip(
                                        new A.BlipExtensionList(
                                            new A.BlipExtension
                                            {
                                                Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                            })
                                    )
                                    {
                                        Embed = relationshipId,
                                        CompressionState = A.BlipCompressionValues.Print
                                    },
                                    new A.Stretch(
                                        new A.FillRectangle())),
                                new PIC.ShapeProperties(
                                    new A.Transform2D(
                                        new A.Offset { X = 0L, Y = 0L },
                                        new A.Extents { Cx = 5d.Inches(), Cy = 2.66.Inches() }), // Width and Height of the image in inches. 1" = 1000000L
                                    new A.PresetGeometry(
                                        new A.AdjustValueList()
                                    )
                                    { Preset = A.ShapeTypeValues.Rectangle }))
                        )
                        { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                )
                {
                    DistanceFromTop = 0U,
                    DistanceFromBottom = 0U,
                    DistanceFromLeft = 0U,
                    DistanceFromRight = 0U,
                    EditId = "50D07946"
                });

    // Append the reference to the specific paragraph that contains the 'tag'.
    wordDoc.MainDocumentPart.Document.Body.Elements<Paragraph>().FirstOrDefault(f => f.InnerText.Contains(tag))?.AppendChild(new Paragraph(new Run(element)));
}

Function for converting an inch into an inch according to Word:

private static long Inches(this double size)
{
    return (long) (size*1000000);
}

EDIT: Here are the contents of the header1.xml. They are the same before and after adding the images.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:hdr xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se wp14"><w:p w:rsidR="007D4EA8" w:rsidRPr="00E6041C" w:rsidRDefault="00292B4C" w:rsidP="00292B4C"><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="24"/></w:rPr></w:pPr><w:r w:rsidRPr="00E6041C"><w:rPr><w:noProof/><w:sz w:val="28"/></w:rPr><w:drawing><wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="251658240" behindDoc="1" locked="0" layoutInCell="1" allowOverlap="1" wp14:anchorId="2F59D91E" wp14:editId="24EB15EA"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="page"><wp:align>right</wp:align></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>-157972</wp:posOffset></wp:positionV><wp:extent cx="7792085" cy="661254"/><wp:effectExtent l="0" t="0" r="0" b="5715"/><wp:wrapNone/><wp:docPr id="1" name="Picture 1"/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="0" name="Picture 1" descr="T:\Reich USA Commercial\Logo\Logos - US\Reich USA Letterhead.png"/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="rId1" cstate="print"><a:extLst><a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}"><a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/></a:ext></a:extLst></a:blip><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="7792085" cy="661254"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln><a:effectLst/><a:extLst><a:ext uri="{53640926-AAD7-44D8-BBD7-CCE9431645EC}"><a14:shadowObscured xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main"/></a:ext></a:extLst></pic:spPr></pic:pic></a:graphicData></a:graphic><wp14:sizeRelH relativeFrom="margin"><wp14:pctWidth>0</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV relativeFrom="margin"><wp14:pctHeight>0</wp14:pctHeight></wp14:sizeRelV></wp:anchor></w:drawing></w:r>
<w:r w:rsidRPr="00E6041C"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>TV</w:t></w:r>
<w:r w:rsidR="007843C2"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>A</w:t></w:r>
<w:r w:rsidRPr="00E6041C"><w:rPr><w:sz w:val="28"/></w:rPr><w:t xml:space="preserve"> Number: </w:t></w:r>
<w:r w:rsidR="00F972A0"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>&lt;</w:t></w:r>
<w:proofErr w:type="spellStart"/><w:r w:rsidR="00F972A0"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>TVCNum</w:t></w:r>
<w:proofErr w:type="spellEnd"/><w:r w:rsidR="00F972A0"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>&gt;</w:t></w:r>
</w:p><w:p w:rsidR="00940058" w:rsidRDefault="00940058"><w:pPr><w:pStyle w:val="Header"/><w:rPr><w:sz w:val="16"/></w:rPr></w:pPr></w:p><w:p w:rsidR="00BB3259" w:rsidRPr="00940058" w:rsidRDefault="00292B4C"><w:pPr><w:pStyle w:val="Header"/><w:rPr><w:sz w:val="16"/></w:rPr></w:pPr><w:r w:rsidRPr="00926942"><w:rPr><w:sz w:val="16"/></w:rPr><w:t xml:space="preserve">Torsional Vibration </w:t></w:r>
<w:r w:rsidR="007843C2"><w:rPr><w:sz w:val="16"/></w:rPr><w:t>Analysis</w:t></w:r>
</w:p><w:p w:rsidR="00BB3259" w:rsidRPr="0037430D" w:rsidRDefault="00BB3259" w:rsidP="00F909DF"><w:pPr><w:tabs><w:tab w:val="center" w:pos="4680"/><w:tab w:val="right" w:pos="9360"/></w:tabs><w:spacing w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:sz w:val="28"/></w:rPr></w:pPr><w:r w:rsidRPr="00292B4C"><w:rPr><w:sz w:val="28"/></w:rPr><w:t xml:space="preserve">Customer: </w:t></w:r>
<w:r w:rsidR="00F972A0"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>&lt;Customer&gt;</w:t></w:r>
<w:r w:rsidR="00F909DF"><w:rPr><w:sz w:val="28"/></w:rPr><w:tab/></w:r>
<w:r w:rsidR="00F909DF"><w:rPr><w:sz w:val="28"/></w:rPr><w:tab/></w:r>
<w:r w:rsidR="00F909DF" w:rsidRPr="0037430D"><w:rPr><w:sz w:val="20"/></w:rPr><w:t xml:space="preserve">Performed </w:t></w:r>
<w:proofErr w:type="gramStart"/><w:r w:rsidR="00F909DF" w:rsidRPr="0037430D"><w:rPr><w:sz w:val="20"/></w:rPr><w:t>By</w:t></w:r>
<w:proofErr w:type="gramEnd"/><w:r w:rsidR="00F909DF" w:rsidRPr="0037430D"><w:rPr><w:sz w:val="20"/></w:rPr><w:t xml:space="preserve">: </w:t></w:r>
<w:r w:rsidR="00F972A0"><w:rPr><w:sz w:val="20"/></w:rPr><w:t>&lt;User&gt;</w:t></w:r>
</w:p><w:p w:rsidR="00AF585E" w:rsidRPr="00BB3259" w:rsidRDefault="00645FF6" w:rsidP="00F909DF"><w:pPr><w:tabs><w:tab w:val="right" w:pos="9360"/></w:tabs><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:noProof/><w:sz w:val="28"/></w:rPr><mc:AlternateContent><mc:Choice Requires="wps"><w:drawing><wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="251660288" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1" wp14:anchorId="26F2E2C8" wp14:editId="4EF2E467"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="page"><wp:posOffset>-74874</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>173822</wp:posOffset></wp:positionV><wp:extent cx="7950241" cy="0"/><wp:effectExtent l="38100" t="19050" r="69850" b="114300"/><wp:wrapNone/><wp:docPr id="3" name="Straight Connector 3"/><wp:cNvGraphicFramePr/><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:cNvCnPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="7950241" cy="0"/></a:xfrm><a:prstGeom prst="line"><a:avLst/></a:prstGeom><a:ln w="12700"><a:solidFill><a:srgbClr val="335BA3"/></a:solidFill></a:ln><a:effectLst><a:outerShdw blurRad="50800" dist="38100" dir="5400000" algn="t" rotWithShape="0"><a:prstClr val="black"><a:alpha val="40000"/></a:prstClr></a:outerShdw></a:effectLst></wps:spPr><wps:style><a:lnRef idx="3"><a:schemeClr val="accent5"/></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent5"/></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent5"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1"/></a:fontRef></wps:style><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic><wp14:sizeRelH relativeFrom="margin"><wp14:pctWidth>0</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV relativeFrom="margin"><wp14:pctHeight>0</wp14:pctHeight></wp14:sizeRelV></wp:anchor></w:drawing></mc:Choice><mc:Fallback><w:pict><v:line w14:anchorId="04485610" id="Straight Connector 3" o:spid="_x0000_s1026" style="position:absolute;z-index:251660288;visibility:visible;mso-wrap-style:square;mso-width-percent:0;mso-height-percent:0;mso-wrap-distance-left:9pt;mso-wrap-distance-top:0;mso-wrap-distance-right:9pt;mso-wrap-distance-bottom:0;mso-position-horizontal:absolute;mso-position-horizontal-relative:page;mso-position-vertical:absolute;mso-position-vertical-relative:text;mso-width-percent:0;mso-height-percent:0;mso-width-relative:margin;mso-height-relative:margin" from="-5.9pt,13.7pt" to="620.1pt,13.7pt" o:gfxdata="UEsDBBQABgAIAAAAIQC2gziS/gAAAOEBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbJSRQU7DMBBF&#xA;90jcwfIWJU67QAgl6YK0S0CoHGBkTxKLZGx5TGhvj5O2G0SRWNoz/78nu9wcxkFMGNg6quQqL6RA&#xA;0s5Y6ir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3TdsAAAAKAQAADwAAAAAAAAAA&#xA;AAAAAACSBAAAZHJzL2Rvd25yZXYueG1sUEsFBgAAAAAEAAQA8wAAAJoFAAAAAA==&#xA;" strokecolor="#335ba3" strokeweight="1pt"><v:stroke joinstyle="miter"/><v:shadow on="t" color="black" opacity="26214f" origin=",-.5" offset="0,3pt"/><w10:wrap anchorx="page"/></v:line></w:pict></mc:Fallback></mc:AlternateContent></w:r>
<w:r w:rsidR="008453E8"><w:t xml:space="preserve">Customer Ref. – No.  </w:t></w:r>
<w:r w:rsidR="00BB3259"><w:t xml:space="preserve"> </w:t></w:r>
<w:r w:rsidR="00F972A0" w:rsidRPr="00BB1CB1"><w:rPr><w:i/></w:rPr><w:t>&lt;</w:t></w:r>
<w:proofErr w:type="spellStart"/><w:r w:rsidR="00F972A0" w:rsidRPr="00BB1CB1"><w:rPr><w:i/></w:rPr><w:t>CustRef</w:t></w:r>
<w:proofErr w:type="spellEnd"/><w:r w:rsidR="00F972A0" w:rsidRPr="00BB1CB1"><w:rPr><w:i/></w:rPr><w:t>&gt;</w:t></w:r>
<w:r w:rsidR="00F909DF"><w:tab/></w:r>
<w:r w:rsidR="00DE1633"><w:rPr><w:sz w:val="16"/></w:rPr><w:t>Mahwah</w:t></w:r>
<w:r w:rsidR="0029773E"><w:rPr><w:sz w:val="16"/></w:rPr><w:t>,</w:t></w:r>
<w:r w:rsidR="00DE1633"><w:rPr><w:sz w:val="16"/></w:rPr><w:t xml:space="preserve"> NJ</w:t></w:r>
<w:r w:rsidR="00EE3F20" w:rsidRPr="00EE3F20"><w:rPr><w:sz w:val="16"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r>
<w:r w:rsidR="0029773E"><w:rPr><w:sz w:val="16"/></w:rPr><w:t>-</w:t></w:r>
<w:r w:rsidR="00EE3F20" w:rsidRPr="00EE3F20"><w:rPr><w:sz w:val="16"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r>
<w:r w:rsidR="00F972A0"><w:rPr><w:sz w:val="16"/></w:rPr><w:t>&lt;Date&gt;</w:t></w:r>
<w:r w:rsidR="0037430D" w:rsidRPr="00EE3F20"><w:rPr><w:b/><w:sz w:val="10"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r>
</w:p></w:hdr>

Upvotes: 6

Views: 4676

Answers (2)

Mark
Mark

Reputation: 429

This is my current solution based on the advice in this thread! The first method gives me the reference id. This id can be reused if I want to add the image more times, but every image insertion should get a unique ID:

AddImageToBody(_imgKReferenceID, $"imgOK{creditNr}", 60, 60, (UInt32)(counter + 100)

public static string InsertAPicture(MainDocumentPart mainPart, string fileName)
{
    try
    {
        ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

        using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        {
            imagePart.FeedData(stream);
        }
        return mainPart.GetIdOfPart(imagePart);
    }
    catch (Exception ex)
    {
        Logger.Log.Error(ex);
        return "";
    }

}

internal static Drawing AddImageToBody(string relationshipId, string name , int w = 60, int h = 60, UInt32 id1=1U, UInt32 id2 = 0U)
{
    System.Drawing.Size size = new System.Drawing.Size(w, h);

    Int64Value width = size.Width/2 * 9525;
    Int64Value height = size.Height/2 * 9525;

    var draw = new Drawing(
        new DW.Inline(
            new DW.Extent() { Cx = width, Cy = height },
            new DW.EffectExtent()
            {
                LeftEdge = 0L,
                TopEdge = 0L,
                RightEdge = 0L,
                BottomEdge = 0L
            },
            new DW.DocProperties()
            {
                Id = (UInt32Value)id1,
                Name = $"{name}"
            },
            new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true }),
            new A.Graphic(
                new A.GraphicData(
                    new PIC.Picture(
                        new PIC.NonVisualPictureProperties(
                            new PIC.NonVisualDrawingProperties()
                            {
                                Id = (UInt32Value)id2,
                                Name = $"{name}"
                            },
                            new PIC.NonVisualPictureDrawingProperties()),
                            new PIC.BlipFill(
                                new A.Blip(
                                    new A.BlipExtensionList(
                                        new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" })
                                    )
                                {
                                    Embed = relationshipId,
                                    CompressionState =
                                    A.BlipCompressionValues.Print
                                },
                                    new A.Stretch(
                                        new A.FillRectangle())),
                                        new PIC.ShapeProperties(
                                            new A.Transform2D(
                                                new A.Offset() { X = 0L, Y = 0L },
                                                new A.Extents() { Cx = width, Cy = height }),
                                                new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
                { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                                                )
        {
            DistanceFromTop = (UInt32Value)0U,
            DistanceFromBottom = (UInt32Value)0U,
            DistanceFromLeft = (UInt32Value)0U,
            DistanceFromRight = (UInt32Value)0U,
            EditId = "50D07946"
        });

    return draw;

}

Upvotes: 0

petelids
petelids

Reputation: 12815

I can see 3 issues with the code you've posted but I'm not sure why you would only see an error if you output more than one image.

The first issue is the Id of the DocProperties. The Id property should be unique amongst all of the DocProperties in the document.

new DW.DocProperties
{
    Id = 1U, //this should be unique amongst ALL DocProperties within the document
    Name = tag // Make sure all of the images have a different name
},

The second issue is very similar; the Id of each of the NonVisualDrawingProperties should also be unique across each NonVisualDrawingProperties instance.

Note that in both cases you will need these values to be unique from the values that already exist in your header. From the header XML that you posted you can see that you already have instances of those properties:

<wp:docPr id="1" name="NormalGraph2" />

and

<pic:cNvPr id="0" name="NormalGraph2.bmp" />

Finally, the third issue I can see is in the code where you add the element. In that code you are finding the Paragraph that contains the tag and then appending a Paragraph to the existing Paragraph. A Paragraph is not allowed to be a child of another Paragraph. Instead, you should just add the Run to the existing Paragraph like so:

wordDoc.MainDocumentPart.Document.Body.Elements<Paragraph>().FirstOrDefault(f => f.InnerText.Contains(tag))?.AppendChild(new Run(element));

or, if you need the separate paragraphs then add the Paragraph after the tag Paragraph against the same Parent node:

var tagNode = wordDoc.MainDocumentPart.Document.Body.Elements<Paragraph>().FirstOrDefault(f => f.InnerText.Contains(tag));
if (tagNode != null)
{
    tagNode.Parent.InsertAfter(new Run(element), tagNode);
}

Upvotes: 4

Related Questions