2
votes

I currently am inserting images with Picture Content Controls, but there appears to be an obvious limitation (by nature of the control) to only 1 IMAGE.

How can I add multiple images at a set location using the OpenXML SDK (2+)?

I did try BookMarks but that doesn't seem to work, just results in a broken document.
I already have quite a bit of code that's building an existing document, so considering the mHtml route is not an option.
Lastly I did try the OpenXML SDK Productivity Tool, but still can't see how to insert multiple images at a set location.

1

1 Answers

1
votes

The problem is that the picture content controls all have some id that points to the same 'blank' image. You have to assign the resource id of each image to the blip.embed property of each content control

This post gives you a brief and effective way of doing this

Open XML – Setting multiple Picture Content Controls by Tag name, without going crazy

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

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

// Select element containing picture control and get the blip element

Bitmap image = new Bitmap(@"F:insert_me.jpg");
SdtElement controlBlock = _mainDocumentPart.Document.Body
    .Descendants<SdtElement>()
        .Where
        (r => 
            r.SdtProperties.GetFirstChild<Tag>().Val == tagName
        ).SingleOrDefault();
// Find the Blip element of the content control.
A.Blip blip = controlBlock.Descendants<A.Blip>().FirstOrDefault();


// Add image and change embeded id.
ImagePart imagePart = _mainDocumentPart
    .AddImagePart(ImagePartType.Jpeg);
using (MemoryStream stream = new MemoryStream())
{
    image.Save(stream, ImageFormat.Jpeg);
    stream.Position = 0;
    imagePart.FeedData(stream);
}
blip.Embed = _mainDocumentPart.GetIdOfPart(imagePart);