Here's my code
- Code: Select all
private static void test()
{
WordprocessingMLPackage wordMLPackage = null;
try {
wordMLPackage = WordprocessingMLPackage.createPackage();
} catch (InvalidFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(panel, "Cannnot create package.");
}
wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", "Hello Word! \n\t" + "Try This!");
byte[] bytes = null;
try {
bytes = convertImageToByteArray();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(panel, "Image file not found.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(panel, "Image file exception: " + e1.toString());
}
try {
addImageToPackage(wordMLPackage, bytes);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(panel, "Cannot add image to package: " + e.toString());
}
try {
wordMLPackage.save(new java.io.File("HelloWord7.docx"));
} catch (Docx4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(panel, "Cannot save image to file.");
}
}
private static void addImageToPackage(WordprocessingMLPackage wordMLPackage,
byte[] bytes) throws Exception {
BinaryPartAbstractImage imagePart =
BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
int docPrId = 1;
int cNvPrId = 2;
Inline inline = imagePart.createImageInline("Filename hint",
"Alternative text", docPrId, cNvPrId, false);
P paragraph = addInlineImageToParagraph(inline);
wordMLPackage.getMainDocumentPart().addObject(paragraph);
}
private static P addInlineImageToParagraph(Inline inline) {
// Now add the in-line image to a paragraph
ObjectFactory factory = new ObjectFactory();
P paragraph = factory.createP();
R run = factory.createR();
paragraph.getContent().add(run);
Drawing drawing = (Drawing) factory.createDrawing();
run.getContent().add(drawing);
((org.docx4j.wml.Drawing) drawing).getAnchorOrInline().add(inline);
return paragraph;
}
private static byte[] convertImageToByteArray() throws IOException {
// get DataBufferBytes from Raster
WritableRaster raster = logo.getRaster();
DataBufferByte data = (DataBufferByte)raster.getDataBuffer();
return (data.getData());
}
I'm getting the following error on line
- Code: Select all
BinaryPartAbstractImage imagePart =
BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
Error returned is: Docx4JException: Error checking image format.
Here's is how 'logo' is loaded,
- Code: Select all
try {
BufferedImage logo = ImageIO.read(getClass().getResourceAsStream("/logo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(panel, "Cannot load logo for word doc");
}
Any help is appreciated, thanks