So up until recently this code worked, and then the users changed the format of the headers.
I am using C# and OpenXML to edit the term [Sample Client] out of a header and replacing it with an Image. This has worked in the past, and actually works with some of the headers, but not others. I can't figure out why. The error I get is "Cannot insert the OpenXmlElement "newChild" because it is part of a tree".
It fails on the line:
textPlaceHolder.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Drawing>(element, textPlaceHolder);
I have found some answers mentioning that I have to use CloneNode, but I am not sure how to implement that, or why. I could use some assistance.
Sorry for the terrible code.
private static string AddImageToHeader(WordprocessingDocument wordDoc, string relationshipId, int xwidth, int yheight)
{
LogWriter log = new LogWriter("");
// Define the reference of the image.
string results = "";
var element =
new DocumentFormat.OpenXml.Wordprocessing.Drawing(
new DW.Inline(
//new DW.Extent() { Cx = 990000, Cy = 792000L },
new DW.Extent() { Cx = xwidth, Cy = yheight },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Header Image"
},
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 = "New Bitmap Image.jpg"
},
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 = xwidth, Cy = yheight }),
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"
});
// Append the reference to body, the element should be in a Run.
// Search for text holder
Text textPlaceHolder = null;
try
{
foreach (var headerPart in wordDoc.MainDocumentPart.HeaderParts)
{
//Gets the text in headers
textPlaceHolder = headerPart.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().Where((x) => x.Text.Contains("Sample Client")).First();
// Insert image (the image created with your function) after text place holder.
textPlaceHolder.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Drawing>(element, textPlaceHolder);
// Remove text place holder.
textPlaceHolder.Remove();
// }
foreach (var currentText in headerPart.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
{
currentText.Text = currentText.Text.Replace("[", "");
currentText.Text = currentText.Text.Replace("]", "");
}
}
}
catch (Exception ex)
{
results = results + "\r\n" + ex.Message.ToString();
log.LogWrite("ERROR adding image to header: "+ex.Message.ToString());
log.ErrorWrite("ERROR adding image to header: " + ex.Message.ToString());
textPlaceHolder = null;
Console.WriteLine(results);
}
if (textPlaceHolder == null)
{
log.ErrorWrite("Error textPlaceHolder is null");
}
else
{
var parent = textPlaceHolder.Parent;
if (!(parent is Run)) // Parent should be a run element.
{
results = results + "\r\nERROR: Parent is not run\r\n";
//log.LogWrite("ERROR: Parent is not run");
}
else
{
// Insert image (the image created with your function) after text place holder.
textPlaceHolder.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Drawing>(element, textPlaceHolder);
// Remove text place holder.
textPlaceHolder.Remove();
}
}
return results;
}