我使用 docx4j 从 doc 模板实现了 doc 生成。具有占位符的模板,在我的代码中,将占位符替换为一个值。问题是 docx4j 不能将占位符作为单独的实体。例如:模板是“tempnew.docx”
welcome to <<name>>,Have a nice day in <<name>>
after running the script, i got the retrieved texts "welcome ", "to", " <<", "name>>" etc.. (check the values of 'content' each time inside the for loop in method 'replaceParagraph' of line 'Text content = (Text) t;')
instead of "welcome ", "to ", "<<name>>" etc..
我的代码:
public static void main(String[] args) throws IOException, Docx4JException {
GenerateDoc genDoc = new GenerateDoc();
String templateFile = "C:\\testdoc\\tempnew.docx";
WordprocessingMLPackage object = genDoc.getTemplate(templateFile);
String toAdd = "India";
genDoc.replaceParagraph( toAdd, object, object.getMainDocumentPart());
genDoc.writeDocxToStream(object, "C:\\testdoc\\docgen.docx");
}
private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private void replaceParagraph( String textToAdd, WordprocessingMLPackage template, ContentAccessor addTo) {
// 1. get the paragraph
String pholderStart ="<<";
String pholderEnd =">>";
int placeHolderStartIndex, placeHolderEndIndex;
List<Object> paragraphs = getAllElementFromObject(template.getMainDocumentPart(), P.class);
P toReplace = null;
for (Object p : paragraphs) {
List<Object> texts = getAllElementFromObject(p, Text.class);
for (Object t : texts) {
Text content = (Text) t;
...
..........}..}