-2
I’m learning to work on Apache POI to work with docx documents and I’m trying to do some checks on an existing document:
XWPFDocument doc = new XWPFDocument(OPCPackage.open("conf/templates/relatorio_modelo_laudo/modelo_laudo.docx"));
this.nPag = doc.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
for (XWPFParagraph p : doc.getParagraphs()) {
    List<XWPFRun> runs = p.getRuns();
    if (runs != null) {
        for (XWPFRun r : runs) {
            String text = r.getText(0);
            if (text != null) {
                while (text.contains("<<")) {
                    String x = text.substring(text.indexOf("<<"), text.indexOf(">>") +2);
                    String result;
                    if (x.contains("{}")) {
                        result = this.getExpressao(x.substring(x.indexOf('{') +1, x.indexOf("}")));
                    } else {
                        String str = x.substring(x.indexOf("<<") +2, x.indexOf(">>"));
                        if (str.equals("nPag")) {
                            result = Integer.toString(nPag);
                        } else {
                            result = params.get(str).isNull() ? "UNDEFINED" : params.get(str).toString();
                        }
                    }
                    text = text.replace(x, result);
                    r.setText(text,0);
                }
            }
        }
    }
}
This would be the method that would take the document and read it, the problem is that in the document I put some fields to be replaced, for example, "<< nPag >>". The system should read, interpret and replace by the variable of the same name, but for some reason Run is cutting my variable, which is in the middle of a paragraph, in 3 parts "... <<" / "nPag" / ">> ...". My variable is coming in 3 different runs.
This book contains << nPag >> pages, electronically numbered...
This is how it is in the document, but this is the only variable that is giving this problem, maybe changing the name solves, but I would like to know the reason... If someone can already explain to me why the command in the second line is not returning the value of the page correctly, I appreciate it (before it was working, updated the document and started to return only 0).
Hugs.
Edit: I tried to rename the variable and still the error persists. I still don’t know why the POI behaves this way only with this variable.