Deleting images in a .docx file

Do we have the ability to remove images from a .docx

file in java using xwpfdocument

? Please answer me as I have been trying to do this for the past week. Code tried:

public static void imageProcess(XWPFDocument document) throws IOException
    {
        List<XWPFPictureData> pic=document.getAllPictures();
        Iterator<XWPFPictureData> iterator=pic.iterator();      
        if (pic.size()>0)
        {   
            for (XWPFParagraph para : document.getParagraphs())
            { 
                List<XWPFRun> runs = para.getRuns();
                for( XWPFRun run : runs ){
                    run.getCTR().removeDrawing(0);
                }
            }
            }
        }  

      

An exception:

 Exception in thread "main" java.lang.IndexOutOfBoundsException
    at org.apache.xmlbeans.impl.store.Xobj.removeElement(Xobj.java:2200)
    at org.apache.xmlbeans.impl.store.Xobj.remove_element(Xobj.java:2230)
    at org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.CTRImpl.removeDrawing(Unknown Source)
    at com.util.DocxUtil.imageProcess(DocxUtil.java:326)
    at com.util.DocxUtil.main(DocxUtil.java:60)   

      

+3


source to share


2 answers


If you get IndexOutOfBoundsException

on a call where you are trying to remove item # 0, then your list is clearly empty. So either do a void check on all the blueprints of your object Run

, or use a for loop that won't run if yours is List<CTDrawing>

empty.



for (XWPFRun run : runs) {
    CTR ctr = run.getCTR();
    List<CTDrawing> lst = ctr.getDrawingList();
    for (int i = 0; i < lst.size(); i++) {
        ctr.removeDrawing(i);
    }
}

      

+2


source


Try the following:



        for (XWPFRun run : paragraph.getRuns())
                {
                     CTDrawing []  arr = run.getCTR().getDrawingArray();

                     for(int k=0; k<arr.length; k++)
                     {
                         run.getCTR().removeDrawing(k);
                     }

                }

      

0


source







All Articles