如何使用java中的ApachePOIxWPF将图片添加到.docx文档中

如何使用java中的ApachePOIxWPF将图片添加到.docx文档中,java,apache-poi,Java,Apache Poi,我使用JavaPOI3.7创建了一个简单的docx文档。XWPF。然后,我添加了一张图片 使用方法XWPFDocument.addpicture(字节[]arg0,int arg1) 由于docx的文件大小增加,图片被“物理地”添加到文档中;但它在MS Word中根本不显示。似乎文档中缺少对图片的引用 怎么做?如何使用ApachePOI进行图片处理?在web上有更多教程的地方,几乎没有XWPF的文档或教程,它解释了段落、运行等的处理 关于这一点,我发现的唯一一件事是:但这一点都没有帮助 非常感谢

我使用JavaPOI3.7创建了一个简单的docx文档。XWPF。然后,我添加了一张图片 使用方法
XWPFDocument.addpicture(字节[]arg0,int arg1)

由于docx的文件大小增加,图片被“物理地”添加到文档中;但它在MS Word中根本不显示。似乎文档中缺少对图片的引用

怎么做?如何使用ApachePOI进行图片处理?在web上有更多教程的地方,几乎没有XWPF的文档或教程,它解释了段落、运行等的处理

关于这一点,我发现的唯一一件事是:但这一点都没有帮助


非常感谢。您提供的bug链接实际上有一个有效的解决方案:


它需要一定程度的黑客,但我正在使用它,它肯定会工作

我使用了docx4j,发现它可以工作。我尝试了POI,但无法使其工作。请查找使用docx4j的代码

public static void main(String[] args) throws Exception {
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    //wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", "Hello World");
    //wordMLPackage.getMainDocumentPart().addParagraphOfText("Text");
     java.io.InputStream is = new java.io.FileInputStream("path\\to\\images.jpg");
// commons-io.jar
     byte[] bytes = IOUtils.toByteArray(is);
     String filenameHint = null;
     String altText = null;
     int id1 = 0;
     int id2 = 1;
     org.docx4j.wml.P p = newImage( wordMLPackage, bytes,filenameHint, altText,id1, id2,6000  );
     // Now add our p to the document
     wordMLPackage.getMainDocumentPart().addObject(p);
     wordMLPackage.save(new java.io.File("helloworld.docx") );
     is.close();
}



public static org.docx4j.wml.P newImage( WordprocessingMLPackage wordMLPackage,
        byte[] bytes,
        String filenameHint, String altText, 
        int id1, int id2, long cx) throws Exception {

        BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

        Inline inline = imagePart.createImageInline(filenameHint, altText,id1, id2, cx,false);

    // Now add the inline in w:p/w:r/w:drawing
        org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
        org.docx4j.wml.P  p = factory.createP();
        org.docx4j.wml.R  run = factory.createR();             
        p.getContent().add(run);       
        org.docx4j.wml.Drawing drawing = factory.createDrawing();               
        run.getContent().add(drawing);               
        drawing.getAnchorOrInline().add(inline);

        return p;

}

我知道这篇文章很老了,但我仍然在发布答案,以便所有正在搜索此答案的人都能使用它。 要在word文档中插入图片,必须编写两个程序。第一个是:-

package org.word.POI;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

/*
Romesh Soni
soni.romesh@gmail.com
*/

public class TestCustom
{

    public static void main(String []a) throws FileNotFoundException, IOException, InvalidFormatException
    {

        CustomXWPFDocument document = new CustomXWPFDocument(new FileInputStream(new File("C:\\Users\\amitabh\\Documents\\Apache POI\\Word File\\new.doc")));
        FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\amitabh\\Documents\\Apache POI\\Word File\\new.doc"));

        String blipId = document.addPictureData(new FileInputStream(new File("C:\\Users\\amitabh\\Pictures\\pics\\3.jpg")), Document.PICTURE_TYPE_JPEG);

        System.out.println(document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG));

        //System.out.println(document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG));
        document.createPicture(blipId,document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG), 500, 500);


        document.write(fos);
        fos.flush();
        fos.close();

    }

}
现在,我在代码中使用了“CustomeXwPFDocument”,您将无法通过任何jar文件获得任何导入,因此必须在包中添加另一个.java类。“CustomXWPFDocument”类的代码如下所示:-

package org.word.POI;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;

import java.io.IOException;
import java.io.InputStream;

public class CustomXWPFDocument extends XWPFDocument
{
    public CustomXWPFDocument(InputStream in) throws IOException
    {
        super(in);
    }

    public void createPicture(String blipId,int id, int width, int height)
    {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        //String blipId = getAllPictures().get(id).getPackageRelationship().getId();


        CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();

        String picXml = "" +
                "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
                "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "         <pic:nvPicPr>" +
                "            <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
                "            <pic:cNvPicPr/>" +
                "         </pic:nvPicPr>" +
                "         <pic:blipFill>" +
                "            <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
                "            <a:stretch>" +
                "               <a:fillRect/>" +
                "            </a:stretch>" +
                "         </pic:blipFill>" +
                "         <pic:spPr>" +
                "            <a:xfrm>" +
                "               <a:off x=\"0\" y=\"0\"/>" +
                "               <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
                "            </a:xfrm>" +
                "            <a:prstGeom prst=\"rect\">" +
                "               <a:avLst/>" +
                "            </a:prstGeom>" +
                "         </pic:spPr>" +
                "      </pic:pic>" +
                "   </a:graphicData>" +
                "</a:graphic>";

        //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try
        {
            xmlToken = XmlToken.Factory.parse(picXml);
        }
        catch(XmlException xe)
        {
            xe.printStackTrace();
        }
        inline.set(xmlToken);
        //graphicData.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("Picture " + id);
        docPr.setDescr("Generated");
    }
}
package org.word.POI;
导入org.apache.poi.xwpf.usermodel.XWPFDocument;
导入org.apache.xmlbeans.XmlException;
导入org.apache.xmlbeans.XmlToken;
导入org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
导入org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
导入org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
导入java.io.IOException;
导入java.io.InputStream;
公共类CustomXWPFDocument扩展了XWPFDocument
{
public CustomXWPFDocument(InputStream in)引发IOException
{
超级(in),;
}
public void createPicture(字符串blipd、int-id、int-width、int-height)
{
最终国际货币单位=9525;
宽度*=EMU;
高度*=EMU;
//字符串blipId=getAllPictures().get(id).getPackageRelationship().getId();
CTInline inline=Create段落().createRun().getCTR().addNewDrawing().addNewInline();
字符串picXml=“”+
"


现在您可以开始飞行了。祝您好运。

优雅的解决方案即将推出,请查看:

您可以等待我的补丁被接受并发布,或者尝试将补丁应用到最新的POI SVN签出(,只读访问链接将起作用)并从源代码构建POI JAR

tsd.tom建议的方法将起作用:

XWPFParagraph par = docx.createParagraph();
XWPFRun run = par.createRun();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_JPEG, "logo.JPG",300,300); 

因为XWPFRun.addPicture不起作用(它会损坏xdoc文件),所以我可以这样处理图片:

    private void addPicture(final String fileName, final int id, int width, int height, final XWPFRun run)
{
    FileInputStream fileInputStream = null;

    try
    {
        fileInputStream = new FileInputStream("/home/maq/ebworkspace/TeamForge_Tools/" + fileName);
        final String blipId = run.getDocument().addPictureData(fileInputStream, Document.PICTURE_TYPE_JPEG);

        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        //String blipId = getAllPictures().get(id).getPackageRelationship().getId();

        final CTInline inline = run.getCTR().addNewDrawing().addNewInline();

        final String picXml = "" + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                + "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                + id
                + "\" name=\"Generated\"/>"
                + "            <pic:cNvPicPr/>"
                + "         </pic:nvPicPr>"
                + "         <pic:blipFill>"
                + "            <a:blip r:embed=\""
                + blipId
                + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                + "            <a:stretch>"
                + "               <a:fillRect/>"
                + "            </a:stretch>"
                + "         </pic:blipFill>"
                + "         <pic:spPr>"
                + "            <a:xfrm>"
                + "               <a:off x=\"0\" y=\"0\"/>"
                + "               <a:ext cx=\""
                + width
                + "\" cy=\""
                + height
                + "\"/>"
                + "            </a:xfrm>"
                + "            <a:prstGeom prst=\"rect\">"
                + "               <a:avLst/>"
                + "            </a:prstGeom>"
                + "         </pic:spPr>"
                + "      </pic:pic>" + "   </a:graphicData>" + "</a:graphic>";

        //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        xmlToken = XmlToken.Factory.parse(picXml);
        inline.set(xmlToken);
        //graphicData.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        final CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);

        final CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("Picture " + id);
        docPr.setDescr("Generated");
    }
    catch (final Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        //close streams 
        if (fileInputStream != null)
        {
            try
            {
                fileInputStream.close();
            }
            catch (final IOException ioEx)
            {
                //can be ignored
            }
        }
    }

}

您尝试过POI 3.8 beta 4吗?一些图片错误自3.7 final以来已修复,因此值得一看升级是否解决了您的问题,唯一的区别是在POI 3.8 beta 4中,方法名称XWPFDocument.addPicture(字节[]arg0,int arg1)更改为XWPFDocument.addPictureData(字节[]arg0,int arg1)-可能需要说明的是,该方法仅将图片数据添加到文档中,而不将图片添加到要在word等中显示的段落中。如何执行此操作的问题仍然没有答案。我认为CTPicture对象(org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture)必须创建并添加到一个段落中。但是,我还没有找到如何做这件事。你尝试调用你想让图片显示的文本运行吗?<代码> Pax= Pox.Dox.CeCudieTebug();XWPFRun Run= PAR。CurrAudio();Run.AdvI图(PIC,XWPFDoptTn.PigTrimyType JPEG,“Logo .jpg”,300300)
无效,MS Word无法读取文档。欢迎使用StackOverflow。您可以通过使用4个空格缩进代码块来创建代码块(或选择整个代码块并单击
{}
图标)。2016年2月,优雅的解决方案仍然不在这里。汉克斯·曼,这帮了大忙。但是,您不需要创建两个程序。您只需使用
createPicture
方法中的代码,就可以随时随地使用。@Amitabh Rajan:是否可以在特定的页面和行中添加图片,并且还可以使用中心对齐?@mageshbab:-dude我认为这是可能的,但我很抱歉,我不能在这一点上帮助你。我去年在POI上做了一个很小的作业,但我认为你说的是可能的。请玩玩代码,我想你会得到答案。我真的很抱歉不能帮你。@AmitabhRanjan你的代码帮助很大,bu您能告诉我如何使用此代码在标题中添加图像Apache poi 3.13(2016年2月)仍然具有issue@Amitabh你能帮我做POI吗??
@Pradeep  Your code

    public static void main(String[] args) throws Exception {
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    //wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", "Hello World");
    //wordMLPackage.getMainDocumentPart().addParagraphOfText("Text");
     java.io.InputStream is = new java.io.FileInputStream("path\\to\\images.jpg");
// commons-io.jar
     byte[] bytes = IOUtils.toByteArray(is);
     String filenameHint = null;
     String altText = null;
     int id1 = 0;
     int id2 = 1;
     org.docx4j.wml.P p = newImage( wordMLPackage, bytes,filenameHint, altText,id1, id2,6000  );
     // Now add our p to the document
     wordMLPackage.getMainDocumentPart().addObject(p);
     wordMLPackage.save(new java.io.File("helloworld.docx") );
     is.close();
}



public static org.docx4j.wml.P newImage( WordprocessingMLPackage wordMLPackage,
        byte[] bytes,
        String filenameHint, String altText, 
        int id1, int id2, long cx) throws Exception {

        BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

        Inline inline = imagePart.createImageInline(filenameHint, altText,id1, id2, cx,false);

    // Now add the inline in w:p/w:r/w:drawing
        org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
        org.docx4j.wml.P  p = factory.createP();
        org.docx4j.wml.R  run = factory.createR();             
        p.getContent().add(run);       
        org.docx4j.wml.Drawing drawing = factory.createDrawing();               
        run.getContent().add(drawing);               
        drawing.getAnchorOrInline().add(inline);

        return p;

 works , but all the above codes does not work, i tried it personally

thanks, a lot.
    private void addPicture(final String fileName, final int id, int width, int height, final XWPFRun run)
{
    FileInputStream fileInputStream = null;

    try
    {
        fileInputStream = new FileInputStream("/home/maq/ebworkspace/TeamForge_Tools/" + fileName);
        final String blipId = run.getDocument().addPictureData(fileInputStream, Document.PICTURE_TYPE_JPEG);

        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        //String blipId = getAllPictures().get(id).getPackageRelationship().getId();

        final CTInline inline = run.getCTR().addNewDrawing().addNewInline();

        final String picXml = "" + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                + "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                + id
                + "\" name=\"Generated\"/>"
                + "            <pic:cNvPicPr/>"
                + "         </pic:nvPicPr>"
                + "         <pic:blipFill>"
                + "            <a:blip r:embed=\""
                + blipId
                + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                + "            <a:stretch>"
                + "               <a:fillRect/>"
                + "            </a:stretch>"
                + "         </pic:blipFill>"
                + "         <pic:spPr>"
                + "            <a:xfrm>"
                + "               <a:off x=\"0\" y=\"0\"/>"
                + "               <a:ext cx=\""
                + width
                + "\" cy=\""
                + height
                + "\"/>"
                + "            </a:xfrm>"
                + "            <a:prstGeom prst=\"rect\">"
                + "               <a:avLst/>"
                + "            </a:prstGeom>"
                + "         </pic:spPr>"
                + "      </pic:pic>" + "   </a:graphicData>" + "</a:graphic>";

        //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        xmlToken = XmlToken.Factory.parse(picXml);
        inline.set(xmlToken);
        //graphicData.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        final CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);

        final CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("Picture " + id);
        docPr.setDescr("Generated");
    }
    catch (final Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        //close streams 
        if (fileInputStream != null)
        {
            try
            {
                fileInputStream.close();
            }
            catch (final IOException ioEx)
            {
                //can be ignored
            }
        }
    }

}
 addPicture(filePath, xdoc.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG), 100, 50, xRun);