在docx4j中的VariableReplace中插入换行符

问题描述 投票:0回答:2

我一直在尝试填写一个Word模板(.docx)文件,其中包含需要替换的占位符。

我能够重写模板,但文本没有换行符 我知道回车或换行( ) 不适用于 .docx 文件。我使用 VariableReplace 方法进行转换,但在使用变量替换时无法放置 br 或factory.createBr()。

任何建议都会非常有帮助。下面是我尝试过的一段代码

    Map<String,String> variableReplaceMap = new HashMap<>();
    Map<String, String> textContent = readTextContentAfterDBExtractionToFillUpTemplate();
    ObjectFactory factory = Context.getWmlObjectFactory();
    P para = factory.createP();
    R rspc = factory.createR();

    String power= textContent.get("Power & Energy");
    String[] powerWithNewLine = skills.split("\\\\n");
    for (String eachLineOfPower : powerWithNewLine) {

        Text eachLineOfPowerTxt = factory.createText();
        eachLineOfPowerTxt .setValue( eachLineOfPower );
        rspc.getContent().add( eachLineOfPowerTxt );
        Br br = factory.createBr(); 
        rspc.getContent().add(br);
        para.getParagraphContent().add(rspc);
        documentPart.addObject(para);
    }
    String str = "";
    for (Object eachLineOfPgrph : para.getParagraphContent()) {
        str = str + eachLineOfPgrph;
    }
    variableReplaceMap.put("POWER", str);
    return variableReplaceMap;
docx4j
2个回答
3
投票

Jason 的链接已失效。 这是当前链接:https://github.com/plutext/docx4j/blob/master/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/VariableReplace.java

如果将来发生更改,只需使用以下函数并将其应用到包含换行符的字符串:

/**
 * Hack to convert a new line character into w:br.
 * If you need this sort of thing, consider using 
 * OpenDoPE content control data binding instead.
 *  
 * @param r
 * @return
 */
private static String newlineToBreakHack(String r) {

    StringTokenizer st = new StringTokenizer(r, "\n\r\f"); // tokenize on the newline character, the carriage-return character, and the form-feed character
    StringBuilder sb = new StringBuilder();
    
    boolean firsttoken = true;
    while (st.hasMoreTokens()) {                        
        String line = (String) st.nextToken();
        if (firsttoken) {
            firsttoken = false;
        } else {
            sb.append("</w:t><w:br/><w:t>");
        }
        sb.append(line);
    }
    return sb.toString();   
}

© www.soinside.com 2019 - 2024. All rights reserved.