Reputation: 437
I am trying to add an image to the word document I want to create from docx4j..
Here goes my code..
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;
}
}
When compiling I am getting the following error...
Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/xmlgraphics/image/loader/ImageContext
My image file is good but getting this error..what could be the prob?
Upvotes: 0
Views: 3918
Reputation: 15863
docx4j has dependencies.
One of them is:
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>xmlgraphics-commons</artifactId>
<version>1.5</version>
</dependency>
You need to add this to your class path.
Upvotes: 3