Hello,
For performance and bandwidth purposes, we need to optimize the sizes of SVG images. It would be great if there were additional ImageOrPrintOptions that allow us to optimize SVG images.
For example, currently the SVG XML generated by Cells includes extraneous whitespace which increases the SVG image size. This is demonstrated by using the attached Workbook SvgShapes.xlsx (12.7 KB) and the following code using Cells for Java version 19.11:
final String xlFile = [WB_PATH] + "SvgShapes.xlsx";
final String shapeName = "Chart 1";
Workbook wb = new Workbook(xlFile);
Shape shape = wb.getWorksheets().get(0).getShapes().get(shapeName);
// Convert the Shape to SVG
ImageOrPrintOptions options = new ImageOrPrintOptions();
options.setSaveFormat(SaveFormat.SVG);
options.setImageType(ImageType.SVG);
options.setDesiredSize(shape.getWidth(), shape.getHeight());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
shape.toImage(baos, options);
byte[] imgBytes = baos.toByteArray();
// Save the ORIGINAL SVG file
Path svgFile = Paths.get(xlFile.replace(".xlsx", "_" + shapeName + "_orig.svg"));
Files.deleteIfExists(svgFile);
Files.write(svgFile, imgBytes);
System.out.format("ORIGINAL SVG image size: %,d bytes.%n", imgBytes.length);
System.out.format("Saved original SVG as: %s%n", svgFile.toString());
// Remove extraneous whitespace
String svgStr = new String(imgBytes, StandardCharsets.UTF_8);
svgStr = svgStr.substring(svgStr.indexOf("<svg "));
svgStr = svgStr.trim().replaceAll("\\n\\s+", "");
imgBytes = svgStr.getBytes(StandardCharsets.UTF_8);
// Re-save trimmed SVG
svgFile = Paths.get(xlFile.replace(".xlsx", "_" + shapeName + "_trimmed.svg"));
Files.deleteIfExists(svgFile);
Files.write(svgFile, imgBytes);
System.out.format("TRIMMED SVG image size: %,d bytes.%n", imgBytes.length);
System.out.format("Saved trimmed SVG as: %s%n", svgFile.toString());
Running the code above, shows the file sizes before and after removing the whitespace.
However, please also consider additional optimizations (beyond whitespace removal) to make the SVG even more compact. For example, a Google search for “reduce SVG file size” yields several relevant results with SVG optimization solutions.
Thank you.