我正在尝试将图像添加到我想要从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
我的图片文件很好,但收到此错误......可能是什么问题?
答案 0 :(得分:2)
docx4j有依赖关系。
其中一个是:
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>xmlgraphics-commons</artifactId>
<version>1.5</version>
</dependency>
您需要将其添加到类路径中。