Search code examples
c#office-interopdesktop-applicationword-automation

How to Draw diagrams (Charts) in word automation using vectors + Ms Graph with C# office interop word library


so heres the code released by Microsoft and i wonder how to insert a chart when getting vectors from an svg file into word in this process?

//Insert a chart.
Word.InlineShape oShape;
object oClassType = "MSGraph.Chart.8";
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, 
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

//Demonstrate use of late bound oChart and oChartApp objects to
//manipulate the chart object with MSGraph.
object oChart;
object oChartApp;
oChart = oShape.OLEFormat.Object;
oChartApp = oChart.GetType().InvokeMember("Application",
BindingFlags.GetProperty, null, oChart, null);

//Change the chart type to Line.
object[] Parameters = new Object[1];
Parameters[0] = 4; //xlLine = 4
oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
null, oChart, Parameters);

//Update the chart image and quit MSGraph.
oChartApp.GetType().InvokeMember("Update",
BindingFlags.InvokeMethod, null, oChartApp, null);
oChartApp.GetType().InvokeMember("Quit",
BindingFlags.InvokeMethod, null, oChartApp, null);
//... If desired, you can proceed from here using the Microsoft Graph 
//Object model on the oChart and oChartApp objects to make additional
//changes to the chart.

//Set the width of the chart.
oShape.Width = oWord.InchesToPoints(6.25f);
oShape.Height = oWord.InchesToPoints(3.57f);

so how to insert diagrams (with vectors) using office interop word ? some help dear developers, thank you ;)


Solution

  • Well Theres no need to use MsGraph as long as theres an existing .svg file , u can approach it like a picture and add it to the document, like this :

    //define a range with the assigned value of end of doc
     Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
    //add image path
    string img = "C:\\Users\\a_shi\\Desktop\\svgsample.svg";
    
    
    // add a picture by passing the image path, using AddPicture method of InlineShapes interface
        wrdRng.InlineShapes.AddPicture(imgpath);
    

    done!