繁体   English   中英

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

[英]How to identify text in TextBox and replace placeholder using docx4j

我现在将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;
}

上面的方法获取所有元素,而在下面的方法中,我将在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);
        }
    }
}

输出为: @@@@elements@@@@Purchase Order No: @@@@elements@@@@#buyer_bill_no# @@@@elements@@@@

无法识别文档中存在的文本框和矩形中的元素。

看起来您的方法getAllElementFromObject递归到ContentAccessor对象; 显然w:pict或其子孙之一未实现ContentAccessor接口:

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

尝试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