How to convert inline SVG Image to PNG Image in GWT using Canvas (gwt-canvas-0.4.0.jar)
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.rcharts.client.category.CategoryDataTable;
import com.rcharts.client.category.line.LineChart;
public class ConvertSvgToPngRaphelChart {
public LineChart drawChart() {
CategoryDataTable<Double> dataTable = new CategoryDataTable<Double>();
/**Making some random data **/
double[] aus = { 20, 10, 10, 20, 30, 40 };
double[] bul = { 15, 25, 15, 45, 55, 45 };
double[] den = { 25, 35, 25, 35, 60, 35 };
double[] gre = { 30, 5, 33, 33, 35, 60 };
double[][] data = { aus, bul, den, gre };
String[] cat = { "2001", "2002", "2003", "2004", "2005", "2006" };
String[] ser = { "Austria", "Bulgaria", "Denmark", "Greece" };
/**Random Data Made**/
for (int i = 0; i < cat.length; i++) {
for (int j = 0; j < ser.length; j++) {
dataTable.add(data[j][i], cat[i], ser[j]);
}
}
LineChart chart = new LineChart(950, 400);
chart.setDataTable(dataTable);
return chart;
}
public void onModuleLoad() {
LineChart lineChart = drawChart();
String svgInnerHTML = lineChart.getElement().getInnerHTML();
String urlSVGMore = "data:image/svg+xml;base64," + base64encode(svgInnerHTML);
final Image svgBase64EncodedImage = new Image(urlSVGMore);
svgBase64EncodedImage.setWidth("900");
svgBase64EncodedImage.setHeight("350");
svgBase64EncodedImage.addLoadHandler(new LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
Canvas canvas = Canvas.createIfSupported();
if (canvas == null) {
RootPanel.get().add(new Label("Sorry, your browser doesn't support the HTML5 Canvas element"));
return;
}
canvas.setWidth("900px");
canvas.setCoordinateSpaceWidth(900);
canvas.setHeight("350px");
canvas.setCoordinateSpaceHeight(350);
Context2d context = canvas.getContext2d();
ImageElement imageElement = ImageElement.as(svgBase64EncodedImage.getElement());
imageElement.setWidth(900);
imageElement.setHeight(350);
context.drawImage(imageElement, 0, 0, imageElement.getWidth(), imageElement.getHeight(), 0, 0, imageElement.getWidth(), imageElement.getHeight());
String pngURI = canvas.toDataUrl();
Image pngImage = new Image(pngURI);
RootPanel.get().add(pngImage);
}
});
}
private static native String base64encode(String str) /*-{
return $wnd.btoa(str);
}-*/;
}