use of org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart in project Java-Tutorial by gpcodervn.
the class ReportFromTemplate method main.
public static void main(String[] args) {
final String XPATH_TO_SELECT_TEXT_NODES = "//w:t";
String fileName = "";
try {
// Populate the Strings that will replace the template text
Map<String, String> map = new HashMap<String, String>();
map.put("Project", "BP Mount");
map.put("Date", "21-Mar-2011");
// C:\\test\\template1.docx is the template file
WordprocessingMLPackage template = WordprocessingMLPackage.load(new File("resources/Template1.docx"));
Parts parts = template.getParts();
HashMap<PartName, Part> partsMap = parts.getParts();
PartName partName = null;
Part part = null;
Set<PartName> set = partsMap.keySet();
for (Iterator<PartName> iterator = set.iterator(); iterator.hasNext(); ) {
PartName name = (PartName) iterator.next();
if (name.getName().equalsIgnoreCase("/word/media/image1.png")) {
part = partsMap.get(name);
partName = name;
}
}
if (part != null && partName != null) {
part = partsMap.get(partName);
BinaryPart binaryPart = (BinaryPart) part;
binaryPart.setBinaryData(fileToBytes(fileToReplace));
}
List<Object> texts = template.getMainDocumentPart().getJAXBNodesViaXPath(XPATH_TO_SELECT_TEXT_NODES, true);
for (Object obj : texts) {
Text text = (Text) ((JAXBElement) obj).getValue();
String textValue = text.getValue();
for (Object key : map.keySet()) {
// textValue = textValue.replaceAll("\\$\\{" + key + "\\}", (String) map.get(key));
textValue = textValue.trim().replace("${" + key + "}", (String) map.get(key));
}
text.setValue(textValue);
}
/*
* Add the other contents here
*/
template.save(new File("output/ReportFromTemplate.docx"));
System.out.println("Done");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Errors");
}
}
use of org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart in project docx4j-template by vindell.
the class Docx4j_SaveDocxImg_S3_Test method saveDocxImg.
/**
* @Description: 提取word图片
*/
public void saveDocxImg(String filePath, String savePath) throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(filePath));
for (Entry<PartName, Part> entry : wordMLPackage.getParts().getParts().entrySet()) {
if (entry.getValue() instanceof BinaryPartAbstractImage) {
BinaryPartAbstractImage binImg = (BinaryPartAbstractImage) entry.getValue();
// 图片minetype
String imgContentType = binImg.getContentType();
PartName pt = binImg.getPartName();
String fileName = null;
if (pt.getName().indexOf("word/media/") != -1) {
fileName = pt.getName().substring(pt.getName().indexOf("word/media/") + "word/media/".length());
}
System.out.println(String.format("mimetype=%s,filePath=%s", imgContentType, pt.getName()));
FileOutputStream fos = new FileOutputStream(savePath + fileName);
((BinaryPart) entry.getValue()).writeDataToOutputStream(fos);
fos.close();
}
}
}
Aggregations