删除.docx文件中的图像 [英] Remove images in .docx file

查看:659
本文介绍了删除.docx文件中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们是否可以选择使用 xwpfdocument 从java中的 .docx 文件中删除图片?因为我试图在过去一周内做这件事,请回复我。
代码尝试:

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 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)   


推荐答案

如果你得到 IndexOutOfBoundsException 在您尝试删除项目#0的调用中,那么您的列表显然是空的。因此要么对运行对象中的所有绘图进行空白检查,要么使用for循环 - 如果你的 List< CTDrawing> ; 为空。

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);
    }
}

这篇关于删除.docx文件中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆