简体   繁体   English

如何在文本框中标识文本并使用docx4j替换占位符

[英]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#" 我现在将docx文件作为可下载文件,我想用数据库中的“ 132564”实际值替换“#buyer_bill_no#”,现在对于普通文本检查文件来说,可以正常工作以供参考,但是当文本在TextBox或矩形中时(如文档中所示)它无法识别可替换元素,即“#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 上面的方法获取所有元素,而在下面的方法中,我将在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@@@@ 输出为: @@@@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; 看起来您的方法getAllElementFromObject递归到ContentAccessor对象; evidently w:pict or one of its descendants does not implement the ContentAccessor interface: 显然w:pict或其子孙之一未实现ContentAccessor接口:

    <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 尝试TraversalUtils或https://github.com/plutext/docx4j/tree/master/src/main/java/org/docx4j/utils中的类之一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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