Reputation: 641
I'm trying to add an image to an existing Word 2010 document using OpenXML SDK 2.5. But when I add the image the image does not get embedded. When I open the document, the image shows the placeholder with a red cross (as if the image cannot be found). I'm using the following code:
string mimetype = String.Empty;
// :
//Find mime type of the image here
// :
imagePart = wpd.MainDocumentPart.AddImagePart(mimetype);
using (FileStream stream = new FileStream(filename, FileMode.Open))
{
image = new Bitmap(stream);
cy = Convert.ToUInt32(image.PhysicalDimension.Height);
cx = Convert.ToUInt32(image.PhysicalDimension.Width);
imagePart.FeedData(stream);
stream.Close();
}
Paragraph para = FindParagraphInAppendix(....); //Find the paragraph to add
if (para != null)
AddImageToParagraph(para, wpd.MainDocumentPart.GetIdOfPart(imagePart),txt, filename,cx,cy);
else
wpd.MainDocumentPart.Document.Body.Append(GetImageWithPara(wpd.MainDocumentPart.GetIdOfPart(imagePart), filename, cx, cy));
wpd.Package.CreateRelationship(imagePart.Uri, System.IO.Packaging.TargetMode.External,wpd.MainDocumentPart.GetIdOfPart(imagePart));
wpd.MainDocumentPart.Document.Save();
In the code for AddImageToParagraph I'm adding the image as follows:
Pic.BlipFill blipFill1 = new Pic.BlipFill();
A.Blip blip1 = new A.Blip() { Embed = relationshipid,
CompressionState = A.BlipCompressionValues.Print };
A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();
When I open the file generated using Winzip, the document.xml.rels file does not contain a relationship ID associated with the embedded image.
When I open the using OpenXML Productivity tool and validate the XML I get the error : "The relationship 'R75a8cc179...' referenced by attribute 'hxxp://schemas.openxmlformats..../relationships:embed' does not exist Can you help?
Thanks!
Upvotes: 2
Views: 2548
Reputation: 641
I've finally figured this out
The issue was after the MainDocumentPart was edited I was only calling wordProcessingDocument.MainDocumentPart.Save()
. I was not calling the Close()
method. Due to this the ImagePart relationship was not being committed into the package. I think the Close()
method causes the relationship to be "written" to word\_rels\document.xml.rels
section of the docx package!
Upvotes: 3