centic9 / poi-on-android

A sample project that shows how Apache POI can be used in an Android application
Apache License 2.0
357 stars 89 forks source link

java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Dimension #75

Closed fribeau closed 11 months ago

fribeau commented 4 years ago

I'm trying to insert an image xlsx but I end up with the following error:

Failed resolution of: Ljava/awt/Dimension;
E/flutter (25638):  at org.apache.poi.ss.util.ImageUtils.getImageDimension(ImageUtils.java:63)
E/flutter (25638):  at org.apache.poi.ss.util.ImageUtils.setPreferredSize(ImageUtils.java:146)
E/flutter (25638):  at org.apache.poi.xssf.usermodel.XSSFPicture.getPreferredSize(XSSFPicture.java:221)
E/flutter (25638):  at org.apache.poi.xssf.usermodel.XSSFPicture.resize(XSSFPicture.java:180)
E/flutter (25638):  at org.apache.poi.xssf.usermodel.XSSFPicture.resize(XSSFPicture.java:155)
E/flutter (25638):  at org.apache.poi.xssf.usermodel.XSSFPicture.resize(XSSFPicture.java:146)

This is my code (in Kotlin) :

val workbook = XSSFWorkbook()

val outputStream = FileOutputStream(File(path, "/poi.xlsx"))
val stream = FileInputStream(File(path, "/img.jpg"))

val helper = workbook.getCreationHelper()
val sheet = workbook.createSheet("Sheet 1")
val drawing = sheet.createDrawingPatriarch()

val anchor = helper.createClientAnchor();
anchor.setAnchorType( ClientAnchor.AnchorType.MOVE_AND_RESIZE )
val pictureIndex = workbook.addPicture(IOUtils.toByteArray(stream), Workbook.PICTURE_TYPE_JPEG);

anchor.setCol1( 0 );
anchor.setRow1( 2);
anchor.setRow2( 3 );
anchor.setCol2( 1 );
val pict = drawing.createPicture( anchor, pictureIndex );
pict.resize();

workbook.write(outputStream)
outputStream.close()
centic9 commented 4 years ago

Android does not provide the java.awt. packages and also actively refuses if you try to add such classes, this means any part of Apache POI which uses java.awt. stuff will currently fail this way.

I did some workaround with shading for java.awt.Color before, you can try to do the same for Dimension, see https://github.com/centic9/poi-on-android/blob/master/poishadow/build.gradle#L39 and https://github.com/centic9/poi-on-android/tree/master/poishadow/src/main/java/org/apache/poi/java/awt

LePat commented 4 years ago

Here is an example how I added some java.awt classes for my personal use: https://github.com/LePat/poi-on-android/commit/d38372bd33860088c533f0838ee8830b3a945859

It can be done for any java.awt classes, I just needed to get cell size depending on text size (Rectagle2D.getWidth with comment in french...).

centic9 commented 11 months ago

Changes in #110 added some more classes from java.awt. This should now provide at least java.awt.Dimension and a few others.

Please consider sending PRs if you add other classes and think they "good enough" for including here.