准备文档如下
import org.apache.commons.io.FileUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import java.io.*;
import java.util.Collection;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class ImageReplacement {
public static void main(String[] args) throws Exception {
File source = getFileFromUserDir("/template/template.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(source);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// 1610171220 为约定好的图片CheckSum数值
BinaryPartAbstractImage imagePart = findBinaryPartAbstractImageByChecksum(1610171220, wordMLPackage);
PartName partName = imagePart.getPartName();
String rid = documentPart.getRelationshipsPart().getRel(partName).getId();
documentPart.getRelationshipsPart().removePart(partName);
BinaryPartAbstractImage insertImagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, getInsertImage());
insertImagePart.getRels().get(0).setId(rid);
wordMLPackage.addTargetPart(insertImagePart);
wordMLPackage.save(new java.io.File("out.docx"));
}
private static File getFileFromUserDir(String path) {
String dir = System.getProperty("user.dir");
return new File(dir + path);
}
private static byte[] getInsertImage() throws IOException {
File file = getFileFromUserDir("/images/replacement.jpeg");
return FileUtils.readFileToByteArray(file);
}
private static BinaryPartAbstractImage findBinaryPartAbstractImageByChecksum(long sum, WordprocessingMLPackage wordMLPackage) {
Collection<Part> parts = wordMLPackage.getParts().getParts().values();
for (Part part : parts) {
if (part instanceof BinaryPartAbstractImage) {
BinaryPartAbstractImage imagePart = (BinaryPartAbstractImage) part;
byte[] bytes = imagePart.getBytes();
if (isCheckSumEqual(sum, bytes)) {
return imagePart;
}
}
}
return null;
}
private static boolean isCheckSumEqual(long sum, byte[] bytes) {
Checksum crc32 = new CRC32();
crc32.update(bytes, 0, bytes.length);
return crc32.getValue() == sum;
}
}
输出如下