1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| public class AddImage { public static void main(String[] args) throws Exception { WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File("D:/XXXX/XXXX.docx")); File file = new File("D:/XXXX/1.png");
InputStream is = new FileInputStream(file); long length = file.length(); 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; } if (offset < bytes.length) { System.out.println("无法完全读取文件" + file.getName()); } is.close();
String filenameHint = null; String altText = null; int id2 = 1;
P p = newImage(wordMLPackage, bytes, filenameHint, altText, id2); wordMLPackage.getMainDocumentPart().addObject(p);
P p2 = newImage(wordMLPackage, bytes, filenameHint, altText, id2, 3000); wordMLPackage.getMainDocumentPart().addObject(p2);
P p3 = newImage(wordMLPackage, bytes, filenameHint, altText, id2, 6000); wordMLPackage.getMainDocumentPart().addObject(p3);
wordMLPackage.save(new File("D:/Desktop/image.docx"));
}
public static P newImage(WordprocessingMLPackage wordMLPackage, byte[] bytes, String filenameHint, String altText, int id2) throws Exception {
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
Inline inline = imagePart.createImageInline(filenameHint, altText, wordMLPackage.getDrawingPropsIdTracker().generateId(), id2, false);
org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory(); 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;
}
public static P newImage(WordprocessingMLPackage wordMLPackage, byte[] bytes, String filenameHint, String altText, int id2, long cx) throws Exception {
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
Inline inline = imagePart.createImageInline(filenameHint, altText, wordMLPackage.getDrawingPropsIdTracker().generateId(), id2, cx, false);
org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory(); 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;
} }
|