Issue
I am unable to add text containing blank lines as separate paragraphs to a word document.
If I try to add the following text that contains 3 different paragraphs.
- Some text here.
- Another text here.
- Another one here.
what I get is 1. Some text here. 2. Another text here. 3. Another one here. as if they were the same paragraph.
Is it possible to add a text containing blank lines as separate paragraphs to a Word document using Apache POI?
public static void addingMyParagraphs(XWPFDocument doc, String text) throws InvalidFormatException, IOException {
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText(text);
run.setFontFamily("Times new Roman");
}
--In the method below MyText variable is a textArea variable that's part of a javaFx application.
public void CreatingDocument() throws IOException, InvalidFormatException {
String theText = myText.getText();
addingMyParagraphs(doc, theText);
FileOutputStream output = new FileOutputStream("MyDocument.docx");
doc.write(output);
output.close();
}
}
Solution
You need to split your text into "paragraphs" and add each paragraph separately to your WORD document. This has nothing to do with JavaFX.
Here is an example that uses text blocks to simulate the text that is entered into the [JavaFX] TextArea
. Explanations after the code.
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class PoiWord0 {
public static void main(String[] args) {
String text = """
1. Some text here.
2. Another text here.
3. Another one here.
""";
String[] paras = text.split("(?m)^[ \\t]*\\r?\\n");
try (XWPFDocument doc = new XWPFDocument();
FileOutputStream output = new FileOutputStream("MyDocument.docx")) {
for (String para : paras) {
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText(para.stripTrailing());
}
doc.write(output);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
I assume that a paragraph delimiter is a blank line, so I split the text on the blank lines. This still leaves the trailing newline character in each element of the array. I use stripTrailing()
to remove that newline.
Now I have an array of paragraphs, so I simply add a new paragraph to the [WORD] document for each array element.
Note that the above code was written using JDK 15.
The regex for splitting the text came from the SO question entitled Remove empty line from a multi-line string with Java
try-with-resources was added in Java 7.
stripTrailing() was added in JDK 11
Answered By - Abra