I need to generate a word document using Apache POI that has multiple colors of text in one single line and then ends with a horizontal line break. Like in the example bellow:
I tried to use mainText.setBorderBetween(Borders.BASIC_THIN_LINES);
to get a horizontal line and it worked but the horizontal line is pushed all the way down and not centered properly. I tried using:
mainTextRun.setColor("FFA500");
mainTextRun.setText("text 1");
mainTextRun.setColor("008000");
mainTextRun.setText("text 2");
mainTextRun.setColor("0000FF");
mainTextRun.setText("text 3");
But it did not produce the desired text as it kept skipping lines as seen here:
I guess your mainText
is a XWPFParagraph
and your mainTextRun
are multiple XWPFRun
created in that XWPFParagraph
. Then the following small Minimal, Reproducible Example works and produces the Word document shown below.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class CreateWordParagraphBorderAndColoredTextRuns {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph mainText = document.createParagraph();
mainText.setBorderBottom(Borders.BASIC_THIN_LINES);
XWPFRun mainTextRun = mainText.createRun();
mainTextRun.setColor("FFA500"); mainTextRun.setText("text 1 ");
mainTextRun = mainText.createRun();
mainTextRun.setColor("008000"); mainTextRun.setText("text 2 ");
mainTextRun = mainText.createRun();
mainTextRun.setColor("0000FF"); mainTextRun.setText("text 3 ");
mainText = document.createParagraph();
FileOutputStream out = new FileOutputStream("./CreateWordParagraphBorderAndColoredTextRuns.docx");
document.write(out);
out.close();
document.close();
}
}
Result: