I want to edit the embedded file inside a DOC file in .NET. I’m currently doing it by adding the edited file as a new node then remove the old shape node
var doc = new Document(inputFile);
DocumentBuilder docBuilder = new DocumentBuilder(doc);
foreach(Shape shape in doc.GetChildNodes(NodeType.Shape, true).ToArray())
{
if(shape.OleFormat?.IsLink == false)
{
// Extract the file
string embeddedFile = @"C:\tmp\embeddedFile.xls";
shape.OleFormat.Save(embeddedFile);
// Do something with the file
// Add it back
docBuilder.MoveTo(shape);
var oleIcon = shape.OleFormat.OleIcon;
shape.Remove();
docBuilder.InsertOleObject(embeddedFile, false, oleIcon, null); // Or InsertOleObjectAsIcon
}
}
Unfortunately I couldn’t find a way to get the original icon in the shape node. If I leave the last parameter to InsertOleObject as null then the default Aspose icon will be used. Can you please tell me how to do that?
You need to pass the last parameter of InsertOleObject to get the desired output.
Following code example shows how to render the shape to image and set it for OLE. Hope this helps you.
var doc = new Document(MyDir + "inputOLE.docx");
DocumentBuilder docBuilder = new DocumentBuilder(doc);
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).ToArray())
{
if (shape.OleFormat?.IsLink == false)
{
// Extract the file
string embeddedFile = MyDir + @"embeddedFile.docx";
shape.OleFormat.Save(embeddedFile);
MemoryStream stream = new MemoryStream();
shape.GetShapeRenderer().Save(stream, new ImageSaveOptions(SaveFormat.Png));
// Do something with the file
// Add it back
docBuilder.MoveTo(shape);
var oleIcon = shape.OleFormat.OleIcon;
//shape.Remove();
Image img = Image.FromStream(stream);
docBuilder.InsertOleObject(embeddedFile, false, oleIcon, img); // Or InsertOleObjectAsIcon
}
}
doc.Save(MyDir + "20.7.docx");
Thanks. It works great. But I still have a problem that the size after inserting the object is slightly bigger from the original file. Everything is scaled up a little bit even though I copied the size from the original one