Wiki
Clone wikiAspose Java for Docx4j / Insert-Image-in-Document
Aspose.Words
builder.insertImage(dataPath + "background.jpg"); builder.insertImage(dataPath + "bg.jpg", RelativeHorizontalPosition.MARGIN, 100, RelativeVerticalPosition.MARGIN, 200, 200, 100, WrapType.SQUARE);
Docx4j
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); // The image to add File file = new File(dataPath + "java_logo.png" ); // Our utility method wants that as a byte array java.io.InputStream is = new java.io.FileInputStream(file ); long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. if (length > Integer.MAX_VALUE) { System.out.println("File too large!!"); } byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { System.out.println("Could not completely read file "+file.getName()); } is.close(); String filenameHint = null; String altText = null; int id1 = 0; int id2 = 1; // Image 1: no width specified org.docx4j.wml.P p = newImage( wordMLPackage, bytes, filenameHint, altText, id1, id2 ); wordMLPackage.getMainDocumentPart().addObject(p); // Image 2: width 3000 org.docx4j.wml.P p2 = newImage( wordMLPackage, bytes, filenameHint, altText, id1, id2, 3000 ); wordMLPackage.getMainDocumentPart().addObject(p2); // Image 3: width 6000 org.docx4j.wml.P p3 = newImage( wordMLPackage, bytes, filenameHint, altText, id1, id2, 6000 ); wordMLPackage.getMainDocumentPart().addObject(p3); // Now save it wordMLPackage.save(new java.io.File(dataPath + "OUT_AddImage.docx") );
Download Source Code
Updated