Relationship error when trying to embed and image into a Word document

巧了我就是萌 提交于 2019-12-13 04:58:42

问题


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.


回答1:


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.




回答2:


You can find a sample @ http://msdn.microsoft.com/en-us/library/bb497430.aspx



来源:https://stackoverflow.com/questions/11203745/relationship-error-when-trying-to-embed-and-image-into-a-word-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!