Good morning,
we need to get images from Excel using Aspose Cells and convert them into base64 string because the images are going inserted into MS Word documents using MS Word.js API.
Using our code, the MS Word.js API returns error because the MIME Type of the image is “application/octet-stream” instead of “image/octet-stream”.
Our base64 string is not compatible with the API and with your conversion tool
We use Aspose Cells version 23.8.
This is our code. We have two methods:
- Get image from chart
public void getImageBase64FromChart() {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setImageType(ImageType.EMF);
opts.setOnePagePerSheet(true);
opts.setSVGFitToViewPort(true);
Worksheet worksheet = currentWorkbook.getWorksheets().get("Charts");
Chart chart = worksheet.getCharts().get("Chart 1");
chart.toImage(outputStream, opts);
String result = Base64.getEncoder().encodeToString(outputStream.toByteArray());
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
- Get image from range
public void getImageBase64FromRange() {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
Range range = currentWorkbook.getWorksheets().getRangeByName("Fin_Highlights");
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setImageType(ImageType.EMF);
opts.setOnePagePerSheet(true);
opts.setSVGFitToViewPort(true);
Worksheet ws = range.getWorksheet();
PageSetup pageSetup = ws.getPageSetup();
pageSetup.setPrintArea(range.getAddress());
pageSetup.setPrintTitleRows("");
pageSetup.setPrintTitleColumns("");
pageSetup.setLeftMargin(0.0);
pageSetup.setRightMargin(0.0);
pageSetup.setTopMargin(0.0);
pageSetup.setBottomMargin(0.0);
List<Integer> section = IntStream.rangeClosed(0, 2).boxed().collect(Collectors.toList());
section.forEach(s -> {
pageSetup.setFirstPageHeader(s, "");
pageSetup.setHeader(s, "");
pageSetup.setFirstPageFooter(s, "");
pageSetup.setFooter(s, "");
});
SheetRender renderer = new SheetRender(ws, opts);
renderer.toImage(0, outputStream);
String result = Base64.getEncoder().encodeToString(outputStream.toByteArray());
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
We have used “Base64.getEncoder().encodeToString(…)” because we do not found, in Aspose cells, methods or commands that help us to save images in base64 string.
Could you explain us if there is anything that solve our problem?
Thanks
Giulio