How to partially bold a Paragraph in Apache POI? (Word Documents)

I been working with Apache POI recently and i can’t figure out how to set a string like this: “Hello World“. This is what i been trying

    XWPFDocument document = new XWPFDocument();
    String path = System.getProperty("user.home")+ "/Desktop/"+ array.get(0); //"array" is an ArrayList<String>
    path = path.replace("\","/");
            
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    String str1 = "Price: ";
    String str2 = array.get(1); // This needs to be Bold
    run.setFontSize(9);
    run.setFontFamily("Arial");
    run.setText(str1);
    run.setBold(true);
    run.setText(str2);
    paragraph.setSpacingBetween(1);
    paragraph.setAlignment(ParagraphAlignment.RIGHT);
    try {
        FileOutputStream output = new FileOutputStream(ruta);
        document.write(output);
        output.close();
        document.close();
    }catch(Exception e) {
        e.printStackTrace();
    }

I know that “run.setBold(true)” its supposed to apply it to the whole parapraph but its the only thing i found for word documents so i need some help to fix this. Thanks for your help.

Answer

In general, a run is a run, and a paragraph is a paragraph. Different things. You can make the run a single word, adjacent words or an entire paragraph. The only thing that matters is a) if you want to “bold” something, then b) you need to “bold” the corresponding run.

Confusing things, in POI you create a “run” in terms of a “paragraph” 🙁

… BUT …

You can have multiple runs – with different attributes – in the SAME paragraph.

For example:

  XWPFParagraph p = doc.createParagraph();
  XWPFRun r1 = p.createRun();
  r1.setText("Some Text");
  r1.setBold(true);
  r2 = p.createRun();
  r2.setText("Goodbye");

I haven’t tried this code, but I believe “Some Text” will be bold, and “Goodbye” won’t. You can also experiment with different syntax, to see what works best for you.

I hope that helps – and good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *