I need to add something to a word document via OpenXML. I've used the Open Xml productivity tool to generate the code and I'm trying to tweak it so it's reusable for all documents.
Apparently a DocProperties object is required, which requires a unique Id. Is there a way to generate these Id's automatically? Or do I need to do something like the code below to find the max Id used and increment from there?
Is there a better way? This seems expensive. I'm using DocumentFormat.OpenXml from the Open XML SDK (v2.5) from Microsoft in C# with .Net 4.0.
static uint getMaxDocPropertyId(WordprocessingDocument doc)
{
return doc
.MainDocumentPart
.Parts
.Select(x => x.OpenXmlPart.RootElement)
.Where(x => x != null)
.SelectMany(x => x.Descendants<Wp.DocProperties>())
.Max(x => x.Id.Value as uint?) ?? 0;
}
This worked for me, but it is essentially doing the same thing. For me, I don't think it can be avoided since the DocProperties I'm looking for belong to images and I have more than one in my document so each one is buried deep inside of a paragraph -> Run -> Drawing -> and a child of Inline.
private uint GetMaxDocPropertyId(WordprocessingDocument doc)
{
return doc
.MainDocumentPart
.RootElement
.Descendants<DocProperties>()
.Max(x => (uint?) x.Id ) ?? 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With