Use JTextPane in Java with HTML to print reports

We are all familiar with the Java Swing class JTextArea. Java also has a method called print associated with the JComponent class that can be used to print a JTextArea contents onto a printer.

JTextArea jt = new JTextArea(); jt.setText(“whatever text you desire”);

The above code segment will print the contents of the JTextArea jt onto a printer. The output will not have special formatting.

If you need to format the output in the JTextArea before printing, like center, bold, italics, even a table, you cannot do that easily without much effort. To the rescue comes the JTextPane class.

JTextPane allows formatting with HTML, thereby making the output look great. Below code segment shows how that is done.

JTextPane jt = new JTextPane();

StringBuffer strBuffer = new StringBuffer();

strBuffer.append("<br><br><b><center>My First Report using JTextPane</center></b>");
String s;

for (int i = 0; i < 10; i++) {
    s = "" + i;

//Now you can code the print() command as done for JTable