0

我正在尝试将图像添加到要从 docx4j 创建的 word 文档中。

这是我的代码..

package presaleshelperapplication;

import java.io.ByteArrayOutputStream;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
 import sun.misc.IOUtils;


 public class PreSalesHelperApplication {

/**
 * @param args the command line arguments
 */
 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("/D:/Development/PreSalesData/sample.jpg");
 // commons-io.jar
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 byte[] bytes = baos.toByteArray();


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

编译时出现以下错误...

线程“main”中的异常 java.lang.NoClassDefFoundError:org/apache/xmlgraphics/image/loader/ImageContext

我的图像文件很好,但出现此错误..可能是什么问题?

4

1 回答 1

2

docx4j 有依赖关系。

其中之一是:

<dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>xmlgraphics-commons</artifactId>
    <version>1.5</version>
</dependency>

您需要将其添加到您的类路径中。

于 2013-07-15T21:02:36.313 回答