|
| 1 | +using Syncfusion.DocIO; |
| 2 | +using Syncfusion.DocIO.DLS; |
| 3 | +using Syncfusion.DocIORenderer; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.IO; |
| 6 | + |
| 7 | +namespace Convert_chart_to_image_and_replace |
| 8 | +{ |
| 9 | + class Program |
| 10 | + { |
| 11 | + static void Main(string[] args) |
| 12 | + { |
| 13 | + //Open the file as Stream. |
| 14 | + using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open)) |
| 15 | + { |
| 16 | + //Load file stream into Word document. |
| 17 | + using (WordDocument wordDocument = new WordDocument(fileStream, FormatType.Docx)) |
| 18 | + { |
| 19 | + List<Entity> charts = wordDocument.FindAllItemsByProperty(EntityType.Chart, null, null); |
| 20 | + foreach (WChart entity in charts) |
| 21 | + { |
| 22 | + WChart chart = (WChart)entity; |
| 23 | + //Get owner paragraph of chart. |
| 24 | + WParagraph paragraph = chart.OwnerParagraph; |
| 25 | + //Get index of the chart in the paragraph. |
| 26 | + int chartIndex = paragraph.ChildEntities.IndexOf(chart); |
| 27 | + //Create an instance of DocIORenderer. |
| 28 | + using (DocIORenderer renderer = new DocIORenderer()) |
| 29 | + { |
| 30 | + //Convert chart to an image. |
| 31 | + using (Stream stream = chart.SaveAsImage()) |
| 32 | + { |
| 33 | + //Create an instance of WPicture. |
| 34 | + WPicture picture = new WPicture(wordDocument); |
| 35 | + //Load image from stream. |
| 36 | + picture.LoadImage((stream as MemoryStream).ToArray()); |
| 37 | + //Set width and height of the image. |
| 38 | + picture.Width = chart.Width; |
| 39 | + picture.Height = chart.Height; |
| 40 | + //Add image to the paragraph at chart index. |
| 41 | + if (chartIndex < paragraph.ChildEntities.Count) |
| 42 | + paragraph.ChildEntities.Insert(chartIndex, picture); |
| 43 | + else |
| 44 | + paragraph.ChildEntities.Add(picture); |
| 45 | + //Remove chart from the paragraph. |
| 46 | + paragraph.ChildEntities.Remove(chart); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + //Create a file stream. |
| 52 | + using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite)) |
| 53 | + { |
| 54 | + //Save the Word document to the file stream. |
| 55 | + wordDocument.Save(outputFileStream, FormatType.Docx); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
0 commit comments