Search code examples
javaapache-poibackendpowerpointslide

Set image background to an existing slide apache poi ppt


I am trying to set image as a background to an specific slide that already exists (with blank background) and has some components (texts and images), but getting an error when opening the ppt created using apache poi. This is the ppt reference:

enter image description here

My code was based on another stackoverflow response but getting error

XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream("test.pptx"));
byte[] picData = IOUtils.toByteArray(new FileInputStream("image.jpg"));
XSLFPictureData pcData = slideShow.getSlides().get(0).getSlideShow().addPicture(picData, PictureData.PictureType.JPEG);
CTBackgroundProperties backgroundProperties = slideShow.getSlides().get(0).getXmlObject().getCSld().addNewBg().addNewBgPr();
CTBlipFillProperties blipFillProperties = backgroundProperties.addNewBlipFill();
CTRelativeRect ctRelativeRect = blipFillProperties.addNewStretch().addNewFillRect();
String idx = slideShow.getSlides().get(0).addRelation(null, XSLFRelation.IMAGES, pcData).getRelationship().getId();
CTBlip blib = blipFillProperties.addNewBlip();
blib.setEmbed(idx);

try (FileOutputStream fileOut = new FileOutputStream("test.pptx")) {
    slideShow.write(fileOut);
}

Thanks for your answer.


Solution

  • In your code

    CTBackgroundProperties backgroundProperties = slideShow.getSlides().get(0).getXmlObject().getCSld().addNewBg().addNewBgPr();
    

    always adds a new background (Bg) to the slide. That's fine with a new created slide. But an existent slide may have a background setting already. And then, after that code line, it would have two background settings. That is not allowed.

    So if the requirement is to change the background setting of an existent slide, then one should at first unset the old background setting before adding a new one.

    In your case:

    ...
      if (slideShow.getSlides().get(0).getXmlObject().getCSld().isSetBg()) {
          slideShow.getSlides().get(0).getXmlObject().getCSld().unsetBg();
      }
      CTBackgroundProperties backgroundProperties = slideShow.getSlides().get(0).getXmlObject().getCSld().addNewBg().addNewBgPr();
    ...