Skip to content

Variables in the header and footer are not replaced with the values #53

@ssriharan

Description

@ssriharan

There are cases where the variable is in the multiple runs, values are not substituted, this is mostly happening with the variables added in header and footer.

#{testVariable} is recognized as #, {testVariable and } runs, so it's not properly replaced with the value.

image

I believe this has to be fixed in the InsertStrategy implementation, something like below;

` public void insert(Insert insert, Variable variable) {
if (!(insert instanceof TextInsert)) {
return;
}
if (!(variable instanceof TextVariable)) {
return;
}

	TextInsert textInsert = (TextInsert) insert;
	TextVariable textVariable = (TextVariable) variable;

	XWPFParagraph paragraph = textInsert.getParagraph();
	TextSegement found = paragraph.searchText(textInsert.getKey().getKey(), new PositionInParagraph());

	if (found != null) {
		if (found.getBeginRun() == found.getEndRun()) {

			for (XWPFRun run : paragraph.getRuns()) {
				String runText = run.getText(0);
				if (StringUtils.contains(runText, textInsert.getKey().getKey())) {
					runText = StringUtils.replace(runText, textVariable.getKey(), textVariable.getValue());
					run.setText(runText, 0);
				}
			}
		} else {
			StringBuilder b = new StringBuilder();
			for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
				XWPFRun run = paragraph.getRuns().get(runPos);
				b.append(run.getText(run.getTextPosition()));
			}
			String connectedRuns = b.toString();

			if (StringUtils.contains(connectedRuns, textInsert.getKey().getKey())) {
				connectedRuns = StringUtils.replace(connectedRuns, textVariable.getKey(), textVariable.getValue());
				XWPFRun partOne = paragraph.getRuns().get(found.getBeginRun());
				partOne.setText(connectedRuns, 0);
			}

			for (int runPos = found.getBeginRun() + 1; runPos <= found.getEndRun(); runPos++) {
				XWPFRun partNext = paragraph.getRuns().get(runPos);
				partNext.setText("", 0);
			}
		}
	}

}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions