Convert Chart to Image for Java

Hey - Wanted to see if you guys realeased the beta update? Can you post a link to the beta download when you get a chance. I think a lot of folks have been waiting for this update :wink:



Thanks.

We are testing and fixing some issues in chart2image feature. Johnson will provide you a beta version here soon.

Hi,

Please try this beta version for Chart2Image feature. Currently the supported properties are:

1. ChartType:
AREA, AREA_STACKED, AREA_100PERCENT_STACKED,
BAR_CLUSTERED, BAR_STACKED, BAR_100PERCENT_STACKED,
BUBBLE,
COLUMN_CLUSTERED, COLUMN_STACKED, COLUMN_100PERCENT_STACKED,
DOUGHNUT,
LINE, LINE_STACKED, LINE_100PERCENT_STACKED,
PIE,
SCATTER, SCATTER_CONNECTED_BY_LINES_WITH_DATA_MARKE, SCATTER_CONNECTED_BY_LINES_WITHOUT_DATA_MARKE,

2. Generated Image file format:
PNG, JPEG

3. Properties of Chart: Axis, Title, Legend, DataLabels

The API is:

void com.aspose.cells.Chart.toImage(String file, ImageOptions options)

Converts this chart to image.

Parameters:
file the image file to be generated.
options settings for generating image. If null will use default options, generated image file format is PNG.

Thank you.

Aspose Team,

I was directed to this forum post through another post about this beta feature. It’s nice to see it finally being implemented - thank you. I was wondering if it is possible to get the toImage() method implemented with an OutputStream too. I have a case where I don’t want to write to a file but to a stream. I’d hate to have to create a temporary file just to get it into a stream.

Thanks,
Frank

Hi Frank,

We will add an overloaded toImage() method for you soon to write images to a stream. Thank you.

The following code is throwing these errors. Any ideas what I’m doing wrong? The workbook saves properly with the correct charts, but I can’t turn the charts into images.

Thanks,
Frank

java.lang.NullPointerException
at com.aspose.cells.ASeries.getType(Unknown Source)
at com.aspose.a.c.a.a(Unknown Source)
at com.aspose.cells.Chart.toImage(Unknown Source)
at com.test.ChartImage.main(ChartImage.java:44)
java.lang.NullPointerException
at com.aspose.cells.ASeries.getType(Unknown Source)
at com.aspose.a.c.a.a(Unknown Source)
at com.aspose.cells.Chart.toImage(Unknown Source)
at com.test.ChartImage.main(ChartImage.java:51)

package com.test;

import com.aspose.cells.CategoryAxis;
import com.aspose.cells.Cells;
import com.aspose.cells.CellsHelper;
import com.aspose.cells.Chart;
import com.aspose.cells.ChartType;
import com.aspose.cells.Color;
import com.aspose.cells.Font;
import com.aspose.cells.ImageFormat;
import com.aspose.cells.ImageOptions;
import com.aspose.cells.Legend;
import com.aspose.cells.LegendPositionType;
import com.aspose.cells.NSeries;
import com.aspose.cells.TickMarkerType;
import com.aspose.cells.ValueAxis;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;

public class ChartImage {

private static Chart chart;
private static String dir = “c:\temp\”;

public static void main( String[] arguments) throws Exception
{
final Workbook wb = new Workbook();
final Worksheet ws = wb.getWorksheets().getActiveSheet();
final Cells c = ws.getCells();

for (int i=1, value=1; i<4; i++)
{
c.getCell(“A” + i).setValue(“R” + i);
for (int j=1; j<5; j++, value++)
c.getCell(CellsHelper.convertColumnIndexToName(j) + i).setValue(value);
}

final Worksheet worksheet = wb.getWorksheets().getActiveSheet();
chart = worksheet.getCharts().addChart(ChartType.COLUMN_CLUSTERED, 5, 1, 18, 4);
drawReportViewerBarChart();
final ImageOptions imgOpts = new ImageOptions();
imgOpts.setImageFormat(ImageFormat.PNG);
try {
chart.toImage(dir + “chart1.png”, imgOpts);
} catch (Exception e) {
e.printStackTrace();
}
chart = worksheet.getCharts().addChart(ChartType.PIE, 5, 6, 18, 9);
drawReportViewerPieChart();
try {
chart.toImage(dir + “chart2.png”, imgOpts);
} catch (Exception e) {
e.printStackTrace();
}
wb.save(dir + “chart.xls”);
}

private static void drawReportViewerPieChart() throws Exception
{
chart.setType(ChartType.PIE);
chart.getNSeries().add(“Sheet1!$A$1:$E$3”, true);
chart.getPlotArea().getArea().setVisible(false);
drawReportViewerChart();
}

private static void drawReportViewerBarChart() throws Exception
{
chart.setType(ChartType.COLUMN_CLUSTERED);
chart.getNSeries().add(“Sheet1!$A$1:$E$3”, true);
chart.getPlotArea().getArea().setForegroundColor(Color.GRAY);
drawReportViewerChart();
}

private static void drawReportViewerChart() throws Exception
{
chart.getTitle().getFont().setBold(true);
chart.getTitle().getFont().setSize(10);
chart.getPlotArea().getBorder().setVisible(false);

NSeries nSeries = chart.getNSeries();
final int size = nSeries.size();
for (int i = 0; i < size; )
chart.getNSeries().get(i).setName(“C” + ++i);

Legend legend = chart.getLegend();
legend.getFont().setSize(8);
legend.getBorder().setVisible(false);
legend.setPosition(LegendPositionType.BOTTOM);
chart.setLegendShown(true);

CategoryAxis ca = chart.getCategoryAxis();
Font f = ca.getTitle().getFont();
f.setSize(10);
f.setBold(true);
ca.getFont().setBold(false);
ca.getFont().setSize(8);
ca.setMajorTickMark(TickMarkerType.OUTSIDE);

ValueAxis va = chart.getValueAxis();
va.getFont().setBold(false);
va.getFont().setSize(8);
va.setMajorTickMark(TickMarkerType.OUTSIDE);
}
}

Hi,

We found the issue as you have mentioned. We will figure it out soon.

Your issue has been logged into our issue tracking system with an issue id: CELLSJAVA-12243.

Thank you.

Hi,

Thank you for considering Aspose.

We will add a toImage() method and fix the bug as soon as possible.

Hi,

Please try this fix. We have fixed the issue of NullPointerException. Also we add added an overloaded method for Chart.toImage:

void com.aspose.cells.Chart.toImage(OutputStream stream, ImageOptions options)

Converts this chart to image.

Parameters:
stream the stream to save generated image.
options settings for generating image.

And for the ImageOptions parameter, now it is not allowed to be null for both toImage methods.

Thank you.

Thanks so much for the quick turnaround. It looks like images are now being created. In my testing, here are few things I noticed of which you may or may not be aware.

1) The colors in the workbook and the image are not the same.
2) The titles are missing in the image.
3) The borders are missing in the pie chart image.
4) The borders around the legend boxes are missing.

- Frank

Hi Frank,

Thanks for your feedback.

Yes, we have noticed all you four mentioned issues. Since the feature is exposed as beta feature at the moment and we have not made it publicly available for the users, it is still on testing purpose. Moreover, we need to make it more stable and precise, hopefully, we can do it before finalizing it.


Thank you.

Hi,

Please find attached the zipped file of latest Aspose.Cells for Java beta release for Chart-to-Image feature. We have fixed the bugs that you have mentioned. For the color issue, since the auto assigned colors are different in Excel2007 and Excel2003, so you need to specify which file format should be used when generating the Image from the newly created Chart:

ImageOptions imgOpts = new ImageOptions();
imgOpts.setImageFormat(ImageFormat.PNG);
//set fashion to let the generated image looks like Excel2003
imgOpts.setFashion(FileFormatType.EXCEL2003);


Thank you.
Hi,
When I try to generate image from chart, I get the following error

java.lang.NullPointerException
at com.aspose.a.f.a(Unknown Source)
at com.aspose.a.i.b(Unknown Source)
at com.aspose.a.n.a(Unknown Source)
at com.aspose.a.i.a(Unknown Source)
at com.aspose.cells.Chart.toImage(Unknown Source)
at com.xxx.x.GenerateReport.main(GenerateReport.java:343) i.e.,
when trying to generate image.
chart.toImage("C:\\world.jpeg",io);
I have added the method for reference below, please help me out. I could understand where it is going wrong exactly.

public static void main(String ar[]){
try {
Workbook workbook = new Workbook();
Worksheets worksheets = workbook.getWorksheets();
//Obtaining the reference of the first worksheet
Worksheet worksheet= worksheets.getSheet(0);
Cells cells = worksheet.getCells();
cells.getCell("A1").setValue(50);
cells.getCell("A2").setValue(100);
cells.getCell("A3").setValue(150);
cells.getCell("A4").setValue(200);
cells.getCell("B1").setValue(60);
cells.getCell("B2").setValue(32);
cells.getCell("B3").setValue(50);
cells.getCell("B4").setValue(40);
cells.getCell("C1").setValue("Q1");
cells.getCell("C2").setValue("Q2");
cells.getCell("C3").setValue("Y1");
cells.getCell("C4").setValue("Y2");
Charts charts = worksheet.getCharts();
Chart chart= charts.addChart(ChartType.PIE,5,0,15,5);
ImageOptions io = new ImageOptions();
io.setImageFormat(ImageFormat.JPEG);
chart.toImage("C:\\world.jpeg",io);

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertImage("C:\\world.JPEG",
RelativeHorizontalPosition.MARGIN,
0,
RelativeVerticalPosition.MARGIN,
0,
50,
60,
WrapType.SQUARE);
doc.save("C:\\HelloWorld.doc");

} catch (Exception e) {
e.printStackTrace();
}
}

Hi,

Thank you for considering Aspose.

We have found your mentioned issues after an initial test. The issue is basically occurring because you are not specifying any NSeries for the chart. Please add the NSeries to the chart (as mentioned in below code) and chart image will get generated successfully. Also, your issue has been registered in our issue tracking system with issue id CELLSJAVA-12880.

Workbook workbook = new Workbook();

Worksheets worksheets = workbook.getWorksheets();

//Obtaining the reference of the first worksheet

Worksheet worksheet= worksheets.getSheet(0);

Cells cells = worksheet.getCells();

cells.getCell(“A1”).setValue(50);

cells.getCell(“A2”).setValue(100);

cells.getCell(“A3”).setValue(150);

cells.getCell(“A4”).setValue(200);

cells.getCell(“B1”).setValue(60);

cells.getCell(“B2”).setValue(32);

cells.getCell(“B3”).setValue(50);

cells.getCell(“B4”).setValue(40);

cells.getCell(“C1”).setValue(“Q1”);

cells.getCell(“C2”).setValue(“Q2”);

cells.getCell(“C3”).setValue(“Y1”);

cells.getCell(“C4”).setValue(“Y2”);

Charts charts = worksheet.getCharts();

Chart chart= charts.addChart(ChartType.PIE ,5,0,15,5);

chart.getNSeries().add( “=A1:C4” , true );

ImageOptions io = new ImageOptions();

io.setImageFormat(ImageFormat.JPEG );

chart.toImage(“C:\world.jpeg”,io);

Thank You & Best Regards,

I have tried the following sample, but it not generating the image. Can you check what is wrong in the code?

import java.lang.reflect.Array;
import java.io.*;
import com.aspose.cells.*;
import com.aspose.slides.*;

public class ChartMaker {

public static void main(String args[]) {

try {
String[] cellsName = new String[] { "A1", "A2", "A3", "A4",
"B1", "B2", "B3", "B4",
"C1", "C2", "C3", "C4",
"D1", "D2", "D3", "D4",
"E1", "E2", "E3", "E4" };

//Array of cell data
int[] cellsValue = new int[] { 67, 86, 68, 91,
44, 64, 89, 48,
46, 97, 78, 60,
43, 29, 69, 26,
24, 40, 38, 25 };

Workbook wb = new Workbook();
Worksheet dataSheet = wb.getWorksheets().addSheet();
String dataSheetName = "DataSheet";
dataSheet.setName(dataSheetName);

//Populate DataSheet with data
int size = Array.getLength(cellsName);
for (int i = 0; i < size; i++) {
String cellName = cellsName[i];
int cellValue = cellsValue[i];
dataSheet.getCells().getCell(cellName).setValue(cellValue);
}

//Add a chart sheet
Worksheet chartSheet = wb.getWorksheets().addSheet(SheetType.CHART);
chartSheet.setName("ChartSheet");
int chartSheetIdx = chartSheet.getIndex();

//Add a chart in ChartSheet with data series from DataSheet
int chartRows = 55, chartCols = 25;
Chart chart = chartSheet.getCharts().addChart(ChartType.COLUMN_CLUSTERED, 0, chartRows, 0, chartCols);
chart.getNSeries().add(dataSheetName + "!A1:E1", false);
chart.getNSeries().add(dataSheetName + "!A2:E2", false);
chart.getNSeries().add(dataSheetName + "!A3:E3", false);
chart.getNSeries().add(dataSheetName + "!A4:E4", false);
//Set ChartSheet an active sheet

//Get Chart as image.
ImageOptions imgOpts = new ImageOptions();
imgOpts.setImageFormat(ImageFormat.PNG);
imgOpts.setFashion(FileFormatType.EXCEL2003);

chart.toImage(new FileOutputStream("D:\\Temp\\chart.png"), imgOpts);

wb.getWorksheets().setActiveSheet(chartSheetIdx);
wb.setOleSize(0, chartRows, 0, chartCols);

//Save the workbook to stream
ByteArrayOutputStream bout = new ByteArrayOutputStream();
wb.save(bout);
wb.write(new FileOutputStream("D:\\Temp\\output.xls"));

Presentation pres = new Presentation();
Slide sld = pres.addEmptySlide();

int slideWidth = (int) pres.getSlideSize().getX() - 1500;

int slideHeight = (int) pres.getSlideSize().getY();
int x = 1500 / 2;
OleObjectFrame oof = sld.getShapes().addOleObjectFrame(x, 0, slideWidth, slideHeight, "Excel.Sheet.8", bout.toByteArray());

com.aspose.slides.Picture pic = new com.aspose.slides.Picture(pres, new FileInputStream("D:\\Temp\\chart.jpeg"));
int picId = pres.getPictures().add(pic);
oof.setPictureId(picId);

//Write the presentation on disk
pres.write(new FileOutputStream("D:\\Temp\\output.ppt"));
System.out.println("successfully completed!!!");

}
catch (Exception e) {
e.printStackTrace();
}
}

}

It generates chart.png, but no data, file size is 0. so when I try to add it to slide, it fails.

Hi,

Thank you for considering Aspose.

Well, I checked you code and the files are generated fine. You need to modify your code a bit as mentioned below:

import java.lang.reflect.Array;

import java.io.*;

import com.aspose.cells.*;

import com.aspose.slides.*;

public class ChartMaker {

public static void main(String args[]) {

try {

String[] cellsName = new String[] { “A1”, “A2”, “A3”, “A4”,

“B1”, “B2”, “B3”, “B4”,

“C1”, “C2”, “C3”, “C4”,

“D1”, “D2”, “D3”, “D4”,

“E1”, “E2”, “E3”, “E4” };

//Array of cell data

int [] cellsValue = new int [] { 67, 86, 68, 91,

44, 64, 89, 48,

46, 97, 78, 60,

43, 29, 69, 26,

24, 40, 38, 25 };

Workbook wb = new Workbook();

Worksheet dataSheet = wb.getWorksheets().addSheet();

String dataSheetName = “DataSheet”;

dataSheet.setName(dataSheetName);

//Populate DataSheet with data

int size = Array.getLength(cellsName);

for (int i = 0; i < size; i++) {

String cellName = cellsName[i];

int cellValue = cellsValue[i];

dataSheet.getCells().getCell(cellName).setValue(cellValue);

}

//Add a chart sheet

Worksheet chartSheet = wb.getWorksheets().addSheet(SheetType.CHART );

chartSheet.setName(“ChartSheet”);

int chartSheetIdx = chartSheet.getIndex();

//Add a chart in ChartSheet with data series from DataSheet

int chartRows = 55, chartCols = 25;

Chart chart = chartSheet.getCharts().addChart(ChartType.COLUMN_CLUSTERED , 0, chartRows, 0, chartCols);

chart.getNSeries().add(dataSheetName + “!A1:E1”, false );

chart.getNSeries().add(dataSheetName + “!A2:E2”, false );

chart.getNSeries().add(dataSheetName + “!A3:E3”, false );

chart.getNSeries().add(dataSheetName + “!A4:E4”, false );

//Set ChartSheet an active sheet

//Get Chart as image.

ImageOptions imgOpts = new ImageOptions();

imgOpts.setImageFormat(ImageFormat.PNG);

imgOpts.setFashion(FileFormatType.EXCEL2003 );

chart.toImage(new FileOutputStream(“D:\Temp\chart.png”), imgOpts);

wb.getWorksheets().setActiveSheet(chartSheetIdx);

wb.setOleSize(0, chartRows, 0, chartCols);

//Save the workbook to stream

ByteArrayOutputStream bout = new ByteArrayOutputStream();

wb.save(bout);

//write method is deprecated, use save method instead

wb.save( new FileOutputStream( “D:\Temp\output.xls” ));

Presentation pres = new Presentation();

Slide sld = pres.addEmptySlide();

int slideWidth = (int ) pres.getSlideSize().getX() - 1500;

int slideHeight = (int ) pres.getSlideSize().getY();

int x = 1500 / 2;

OleObjectFrame oof = sld.getShapes().addOleObjectFrame(x, 0, slideWidth, slideHeight, “Excel.Sheet.8”, bout.toByteArray());

//File Extension should be PNG instead of JPEG

com.aspose.slides.Picture pic = new com.aspose.slides.Picture(pres, new FileInputStream( “D:\Temp\chart.png” ));

int picId = pres.getPictures().add(pic);

oof.setPictureId(picId);

//Write the presentation on disk

pres.write(new FileOutputStream(“D:\Temp\output.ppt”));

System.out .println(“successfully completed!!!”);

}

catch (Exception e) {

e.printStackTrace();

}

}

}

Thank You & Best Regards,

I copied the code you have updated.

My issue is the file “D:\Temp\chart.png” generated using the toImage method is empty, size 0. Please let me know is there anything wrong in the code.

Chart chart = chartSheet.getCharts().addChart(ChartType.COLUMN_CLUSTERED , 0, chartRows, 0, chartCols);

chart.getNSeries().add(dataSheetName + “!A1:E1”, false );

chart.getNSeries().add(dataSheetName + “!A2:E2”, false );

chart.getNSeries().add(dataSheetName + “!A3:E3”, false );

chart.getNSeries().add(dataSheetName + “!A4:E4”, false );

//Set ChartSheet an active sheet

//Get Chart as image.

ImageOptions imgOpts = new ImageOptions();

imgOpts.setImageFormat(ImageFormat.PNG);

imgOpts.setFashion(FileFormatType.EXCEL2003 );

chart.toImage(new FileOutputStream(“D:\Temp\chart.png”), imgOpts);

sorry...

its working fine with the version posted in <A href="</A>. </P> <P>I was trying with Aspose.CellsV2.1.1.10b, which was failing.</P> <P>Thanks</P> <P>Muhammed</P>

Hello again,

I see through other posts that there is a newer beta version than I currently tried with this feature. I’ll download that to see how it is working. My reason for the new post really is to see if there is any information I can gather on to when the release jar (not beta) with this feature will be available. We do own a license and I’m trying to to figure out when we can remove our other implementation of Excel workbooks. We want to use yours exclusively, but can’t until this feature is available.

Thanks in advance,
Frank

Hi Frank,

We are scheduled to release the next official version (Aspose.Cells for Java) that will support Chart -to- Image feature very soon.

However, you can use the attached version/fix v2.1.1.27, it 's an intermediate kind of build (not beta version) but will behave like an official release that supports Chart -to- Image feature with some enhancements and you can use it as long as you wish for you need in your project as it works fine. It’s not been so long time since we introduced the first beta version for Chart -to- Image feature for the users but it is getting mature and enhanced a bit now.


Thank you.