Positioning an Image in the middle of a cell using ApachePOI

55 Views Asked by At

I am attempting to position an image to the middle of a cell within an excel sheet in a Scala app. I am using ApachePOI version 5.0.0. However, my logic only renders the image to the top left of the cell.

How can I position the image in the middle within a given cell. This is my code logic:

  def addImageToCell(imagePath: String, sheet: XSSFSheet, columnIdx: Int, rowNum: Int): Unit = {
    val fis = Files.newInputStream(Path.of(imagePath))

    val pictureBytes = IOUtils.toByteArray(fis)
    val pictureIdx   = sheet.getWorkbook.addPicture(pictureBytes, Workbook.PICTURE_TYPE_PNG)
    fis.close()

    val helper  = sheet.getWorkbook.getCreationHelper
    val drawing = sheet.createDrawingPatriarch()

    val anchor = helper.createClientAnchor
    anchor.setCol1(columnIdx)
    anchor.setRow1(rowNum)

    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE)

    // load image and get its dimensions
    val bufferedImg       = ImageIO.read(new File(imagePath))
    val originalDimension = new Dimension(bufferedImg.getWidth, bufferedImg.getHeight)

    // get the cell's width & height in pixels
    val colWidthInPixels  = Math.round(sheet.getColumnWidthInPixels(columnIdx))
    val rowHeightInPixels = Math.round(sheet.getRow(rowNum).getHeightInPoints / 72 * 96)

    // calculate scale factor
    val scaleX = colWidthInPixels.toDouble / originalDimension.width
    val scaleY = rowHeightInPixels.toDouble / originalDimension.height

    // use the smaller scale factor to ensure the image fits within the cell
    val scale = Math.min(scaleX, scaleY)
    // makes certain that the scale factor cannot be below "0.1" - else the images will be too tiny
    val revisedScale = Math.max(scale, 0.1)

    // resize image
    val picture: Picture = drawing.createPicture(anchor, pictureIdx)
    picture.resize(revisedScale)

    // calculate the scaled image's new height & width
    val scaledWidth  = (originalDimension.width * revisedScale).toInt
    val scaledHeight = (originalDimension.height * revisedScale).toInt

    // calculate how much to move the image by in order to center it in the cell
    val moveX = (colWidthInPixels - scaledWidth) / 2
    val moveY = (rowHeightInPixels - scaledHeight) / 2

    // move the image to be centered in the cell
    anchor.setDx1(moveX)
    anchor.setDy1(moveY)
  }

Any assistance will be highly appreciated.

0

There are 0 best solutions below