Last active
May 11, 2021 08:22
-
-
Save szymonk92/d855ec1d702bbe6aec6c8a084b733d26 to your computer and use it in GitHub Desktop.
insert image to PPTX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final XSLFSlide graphSlide = slideShow.createSlide(layoutMap.get(graphLayout).get(0)); | |
PictureData.PictureType graphpictype = PictureData.PictureType.PNG; | |
XSLFPictureData graphidx = null; | |
try { | |
final byte[] graphPictureData; | |
try (InputStream is = new FileInputStream(graphpict)) { | |
graphPictureData = IOUtils.toByteArray(is); | |
} | |
graphidx = slideShow.addPicture(graphPictureData, graphpictype); | |
} catch (Exception e) { | |
getLogger().log(Level.FINE, "slideShow.addPicture(graphpictureData, graphpictype)"); | |
} | |
for (XSLFTextShape textShape : graphSlide.getPlaceholders()) { | |
CTShape sh = (CTShape) textShape.getXmlObject(); | |
CTPlaceholder ph = sh.getNvSpPr().getNvPr().getPh(); | |
if (ph != null && graphidx != null) { | |
STPlaceholderType.Enum pType = ph.getType(); | |
if (pType == STPlaceholderType.PIC) { | |
final Rectangle2D anchor = textShape.getAnchor(); | |
final XSLFPictureShape pic; | |
pic = graphSlide.createPicture(graphidx); | |
double ratio; | |
// try to keep image ratio of x/y | |
try { | |
final BufferedImage i = ImageIO | |
.read(new ByteArrayInputStream(pic.getPictureData().getData())); | |
ratio = (double) i.getHeight() / (double) i.getWidth(); | |
double stretchedRatio = anchor.getHeight() / anchor.getWidth(); | |
if (ratio > 0 && stretchedRatio > ratio) { | |
final double new_cy = anchor.getWidth() * ratio; | |
final double new_y = anchor.getMinY() + (anchor.getHeight() - new_cy) / 2; | |
anchor.setRect(anchor.getMinX(), new_y, anchor.getWidth(), new_cy); | |
} else if (ratio > 0) { | |
final double new_cx = anchor.getHeight() / ratio; | |
final double new_x = anchor.getMinX() + (anchor.getWidth() - new_cx) / 2; | |
anchor.setRect(new_x, anchor.getMinY(), new_cx, anchor.getHeight()); | |
} | |
} catch (Exception e) { | |
// do nothing, pic is stretched :-( | |
} | |
// remove the placeholder shape | |
graphSlide.removeShape(textShape); | |
// insert a picture instead | |
pic.setAnchor(anchor); | |
} else { | |
for (XSLFTextParagraph paragraph : textShape.getTextParagraphs()) { | |
for (XSLFTextRun run : paragraph.getTextRuns()) { | |
run.setText(handleReplaceTags(run.getRawText(), data.get(0))); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment