Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove images in .docx file

Tags:

java

image

xwpf

Do we have the option to remove pictures from .docx file in java using xwpfdocument? Please reply me since I'm trying to do it for past one 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);
                }
            }
            }
        }  

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)   
like image 779
Sherin Avatar asked Sep 16 '25 12:09

Sherin


1 Answers

If you get an IndexOutOfBoundsException on a call where you try to remove item #0, then your list is obviously empty. So either do an emptiness check on all the drawings in your Run object, or use a for loop - which won't execute if your List<CTDrawing> is 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);
    }
}
like image 191
blagae Avatar answered Sep 19 '25 04:09

blagae