Question

I add a PNG image to a word 2010 document like this:

var imagePart = report.MainDocumentPart.AddImagePart(ImagePartType.Png);
var imagePath = Path.Combine(imageFolder, "1.png");
var stream = new FileStream(imagePath, FileMode.Open);
imagePart.FeedData(stream);
stream.Close();

I find the blip element of an empty Picture content control and change its reference property to point to the new image:

var blip = image.Descendants<Blip>().Single();
blip.Embed = report.MainDocumentPart.GetIdOfPart(imagePart);

I save the generated document, and validate it using the Open XML Productivity Tool. I get this error:

The relationship 'Ra4d8ccdc5256bb1' referenced by attribute 'http://schemas.openxmlformats.org/officeDocument/2006/relationships:embed' does not exist.

What are relationships? Why doesn't AddImagePart create one? How do I fix this error? When I open the generated document in Word the image doesn't show up.

Was it helpful?

Solution

I've found a solution. I don't know why, but I had to enclose

WordprocessingDocument report = WordprocessingDocument.Open(path, true)

with a using statement like this:

using(WordprocessingDocument report = WordprocessingDocument.Open(path, true)) {
    //embed the image
}

withot using the document wasn't saved properly: relationships weren't created.

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top