-1

i want to Load a template word document and add content to it and save it as new document. here is what i found :

private static WordprocessingMLPackage getTemplate(String name) throws Docx4JException, FileNotFoundException {
  WordprocessingMLPackage template = WordprocessingMLPackage.load(new java.io.File(name));
  return template;
}

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 static void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder) {
  List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class);
  for (Object text : texts) {
    Text textElement = (Text) text;
    if (textElement.getValue().equals(placeholder)) {
      textElement.setValue(name);
    }
  }
}

private void writeDocxToStream(WordprocessingMLPackage template, String target) throws IOException, Docx4JException {
  File f = new File(target);
  template.save(f);
}

i created i sample.docx file in the drive D, and then i called the main method :

public static void main(String[] args) throws Docx4JException, Exception  {
  WordprocessingMLPackage template = getTemplate("D:\\sample.docx");
  replacePlaceholder (template,"fayza", "nom");
}

unfortunately this is not working , it guess the template cant load , i tried but still not working, any help please

Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52

1 Answers1

0

You don't invoke writeDocxToStream?

Also, your code contains:

if (textElement.getValue().equals(placeholder))

You probably want contains, not equals. Its always worth unzipping your docx and looking at the XML to understand the problem better.

In any case, this is over complicated and inefficient, since you create a new and potentially large List.

See instead VariableReplace in the docx4j samples, or use content control data binding.

JasonPlutext
  • 15,352
  • 4
  • 44
  • 84