Skip to content

Commit

Permalink
Keep the formatting of runs (#259)
Browse files Browse the repository at this point in the history
As in 25ecd54 runs were created
anew on text replacement, previous
formatting was not preserved.
To fix this, the text of the first run
is now set to "", and the replacement
text is inserted
  • Loading branch information
AntonOellerer authored Oct 10, 2024
1 parent aa68318 commit 0d0a6ad
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ plugins {
}

group 'com.docutools'
version = '4.2.5'
version = '4.2.6'

java {
toolchain {
Expand Down
14 changes: 11 additions & 3 deletions src/main/java/com/docutools/jocument/impl/word/WordUtilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,20 @@ public static String toString(XWPFParagraph paragraph) {
public static void replaceText(XWPFParagraph paragraph, String newText) {
String[] lines = newText.split("(\\r\\n|\\r|\\n)");
List<XWPFRun> runs = paragraph.getRuns();
XWPFRun run = runs.isEmpty() ? paragraph.createRun() : runs.get(0);
removeRunText(run);
insertLines(lines, run);
// When deleting a run from a paragraph, the collection keeping the runs shrinks to fit to the new size
// If we delete the runs with indices 1,2,3...,x, the second half of the delete operations fails silently
// To avoid this, we simply delete the first run x times.
IntStream.range(0, runs.size()).forEach(value -> paragraph.removeRun(0));
XWPFRun run = paragraph.createRun();
insertLines(lines, run);
IntStream.range(1, runs.size()).forEach(value -> paragraph.removeRun(0));
}

private static void removeRunText(XWPFRun run) {
int sizeOfTextArray = run.getCTR().sizeOfTArray();
for (int i = 0; i < sizeOfTextArray; i++) {
run.setText("", i);
}
}

private static void insertLines(String[] lines, XWPFRun run) {
Expand Down

0 comments on commit 0d0a6ad

Please sign in to comment.