简体   繁体   中英

How to identify text in TextBox and replace placeholder using docx4j

I have docx file as downloadable file now I want to replace "#buyer_bill_no#" with actual value from database say "132564" now this is working fine for normal text check file for reference but when text is in TextBox or rectangle as seen in document its not able to identify replaceable element ie "#buyer_bill_no#"

private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) throws Docx4JException {


    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;
}

The above method gets all elements and in below method I am printing all elements in doc

private void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder) throws Docx4JException {

    List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class);
    for (Object text : texts) {

        Text textElement = (Text) text;
        System.out.println("@@@@elements@@@@"+textElement.getValue());
        if (textElement.getValue().equals(placeholder)) {
            textElement.setValue(name);
        }
    }
}

output is : @@@@elements@@@@Purchase Order No: @@@@elements@@@@#buyer_bill_no# @@@@elements@@@@

not identifying elements in textbox and rectangle present in document.

Looks like your method getAllElementFromObject recurses into ContentAccessor objects; evidently w:pict or one of its descendants does not implement the ContentAccessor interface:

    <w:pict>
      <v:rect >
        <v:textbox>
          <w:txbxContent>
            <w:p>
              <w:r>
                <w:t>#buyer_bill_no#</w:t>
              </w:r>

Try TraversalUtils, or one of the classes in https://github.com/plutext/docx4j/tree/master/src/main/java/org/docx4j/utils

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM