我需要用图片替换图片内容控件。代码运行正常,但当 Word 尝试打开文件时,它报告Catastophic failure:
代码基本上是来自 docx4j 示例的ImageAdd类的调整版本。有趣的是,转换为 PDF 的文档显示正常。
List<SdtElement> contentControls = findContentControls(wordMLPackage.getMainDocumentPart(InputStream));
for (SdtElement contentControl : contentControls) {
for (Object ob : contentControl.getSdtContent().getContent()) {
traverseEelements(ob, value);
}
}
static List<SdtElement> findContentControls(ContentAccessor container) throws Docx4JException, JAXBException {
List<SdtElement> sdtElements = new LinkedList<SdtElement>();
for (Object o : container.getContent()) {
Object unwrapped = XmlUtils.unwrap(o);
if (unwrapped instanceof SdtElement) {
sdtElements.add((SdtElement) unwrapped);
}
if (unwrapped instanceof ContentAccessor) {
List<SdtElement> list = findContentControls((ContentAccessor) unwrapped);
sdtElements.addAll(list);
}
}
return sdtElements;
}
private void traverseEelements(Object object, String value) {
if (object instanceof org.docx4j.wml.Text) {
Text text = (org.docx4j.wml.Text) object;
text.setValue(value);
} else if (object instanceof ContentAccessor) {
ContentAccessor contentAccessor = (ContentAccessor) object;
for (Object ob : contentAccessor.getContent()) {
traverseEelements(ob, value);
}
} else if (object instanceof JAXBElement) {
Object v = ((JAXBElement<?>) object).getValue();
if (v instanceof ContentAccessor) {
ContentAccessor contentAccessor = (ContentAccessor) v;
for (Object ob : contentAccessor.getContent()) {
traverseEelements(ob, value);
}
} else if (v instanceof org.docx4j.wml.Text) {
Text text = (org.docx4j.wml.Text) v;
text.setValue(value);
} else if (v instanceof org.docx4j.wml.Drawing) {
Drawing drawing = (Drawing) v;
try {
File file = new File("C://Users//user//Pictures//test.png" );
java.io.InputStream is = new java.io.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;
}
// 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;
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes );
Inline inline = imagePart.createImageInline(filenameHint, altText, id1, id2, false);
drawing.getAnchorOrInline().add(inline);
} catch(Exception e) {
logger.error(e);
}
} else {
logger.error("unspupported element found: " + object.getClass());
}
} else {
logger.error("unspupported element found: " + object.getClass());
}
}
编辑