Free Support Forum - aspose.com

Mailmerge chart into Word Template

OK. Here what I want.

I have a word document template with two places where I need to insert two different charts.

I can set two mergefields named as follows: Image: XXX and Image: YYY

I need you to show me the complete code sample to generate chart into memory and insert to the word by their mergefield name.

I have seen some code displayed over here, but not as complete as I want.

Thanks.

Francis

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. You can use Aspose.Chart component for generating charts in memory. For example here simple code that shows how to achieve this during mail merge:

public void Test002()

{

//The template contains only two mergefields

//Image:XXX and Image:YYY, here we create array with field names

string[] names = { "XXX", "YYY" };

//As a value of field you can use anything.

//We will use Integer that limits max value of Random.

object[] values = { 10, 100 };

//Open template

Document doc = new Document(@"Test002\in.doc");

//Add event handler

doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField001);

//Execute mail merge

doc.MailMerge.Execute(names, values);

//Save output document

doc.Save(@"Test002\out.doc");

}

void MailMerge_MergeImageField001(object sender, MergeImageFieldEventArgs e)

{

int maxValue = (int)e.FieldValue;

//Create a chart.

Aspose.Chart.Chart lineChart = new Aspose.Chart.Chart();

//Set chart size

lineChart.Height = 300;

lineChart.Width = 400;

//Create new Series

Aspose.Chart.Series lineSeries = new Aspose.Chart.Series();

lineSeries.ChartType = Aspose.Chart.ChartType.Line;

//Lets use field name as a name of Series

lineSeries.Name = e.FieldName;

//Create few datapoints

Random rnd = new Random();

for (int x = 0; x < 10; x++)

{

lineSeries.DataPoints.Add(new Aspose.Chart.DataPoint(x, rnd.Next(maxValue)));

}

//Fill a series

lineChart.SeriesCollection.Add(lineSeries);

//Save chatr in EMF format

MemoryStream ms = new MemoryStream();

lineChart.Save(ms, ImageFormat.Emf);

//Insert chart as EMF

e.ImageStream = ms;

}

I also attached template and output document.

Please see the following link to learn more about Aspose.Chart:

http://www.aspose.com/documentation/visual-components/aspose.chart-for-.net/product-overview.html

Hope this helps.

Best regards.

Thanks. I will try that to see whether it works.

Francis