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

时间:2015-04-10 07:25:57

标签: java jaxb docx4j

我有docx文件为downloadable file现在我想用数据库中的实际值替换“#buyer_bill_no#”并说“132564”现在这对于普通文本检查文件可以正常工作以供参考但是当文本在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@@@@

不识别文档中的文本框和矩形中的元素。

1 个答案:

答案 0 :(得分:0)

看起来你的方法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

中的一个类