In this article, we will explain how to copy an existing chart within the same PowerPoint document or between PowerPoint documents by using Spire.Presentation. Below example called a main method public IChart CreateChart(IChart baseChart, RectangleF rectangle, int nIndex).
There are three Parameters passed in this method:
- baseChart: The source chart.
- rectangle: The area that the chart will be copied to.
- nIndex: The index of the rectangle shape. For example, -1 means append it as the last shape of the slide, 0 means append as the first shape.
Now refer to the following steps:
Copy chart within the same PowerPoint document
Step 1: Instantiate a Presentation object and load the PowerPoint document.
Presentation ppt = new Presentation(); ppt.LoadFromFile("Sample.pptx");
Step 2: Get the chart that is going to be copied.
IChart chart = ppt.Slides[0].Shapes[0] as IChart;
Step 3: Copy the chart from the first slide to the specified location of the second slide within the same document.
ppt.Slides[1].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), 0);
Step 4: Save the document.
ppt.SaveToFile("TestResult.pptx", FileFormat.Pptx2010);
Screenshot of copying chart within the same PowerPoint document:
Copy chart between PowerPoint documents
Step 1: Load the first PowerPoint document.
Presentation ppt1 = new Presentation(); ppt1.LoadFromFile("Sample.pptx");
Step 2: Get the chart that is going to be copied.
IChart chart = ppt1.Slides[0].Shapes[0] as IChart;
Step 3: Load the second PowerPoint document.
Presentation ppt2 = new Presentation(); ppt2.LoadFromFile("Dest.pptx");
Step 4: Copy chart from the first document to the specified location of the second document.
ppt2.Slides[0].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), -1);
Step 5: Save the second document.
ppt2.SaveToFile("TestResult2.pptx", FileFormat.Pptx2010);
Screenshot of copying chart between PowerPoint documents:
Full code:
Copy chart within the same PowerPoint document
using System.Drawing; using Spire.Presentation; using Spire.Presentation.Charts; namespace Copy_Chart { class Program { static void Main(string[] args) { Presentation ppt = new Presentation(); ppt.LoadFromFile("Sample.pptx"); IChart chart = ppt.Slides[0].Shapes[0] as IChart; ppt.Slides[1].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), 0); ppt.SaveToFile("TestResult.pptx", FileFormat.Pptx2010); } } }
Copy chart between PowerPoint documents
using System.Drawing; using Spire.Presentation; using Spire.Presentation.Charts; namespace Copy_Chart { class Program { static void Main(string[] args) { Presentation ppt1 = new Presentation(); ppt1.LoadFromFile("Sample.pptx"); IChart chart = ppt1.Slides[0].Shapes[0] as IChart; Presentation ppt2 = new Presentation(); ppt2.LoadFromFile("Dest.pptx"); ppt2.Slides[0].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), -1); ppt2.SaveToFile("TestResult2.pptx", FileFormat.Pptx2010); } } }