Thursday, August 25, 2011

Printing with JEditorPane

The following is an illustration of printing with Java. Here I have used JEditorPane and PrinterJob. What printed in this example is an html page.


package ds.demo.service;

import java.awt.print.PrinterJob;
import java.text.MessageFormat;

import javax.swing.JEditorPane;

public class Test {

    static MessageFormat head = new MessageFormat("");
    static MessageFormat foot = new MessageFormat("");

    public static void main(String[] args) throws Exception {

        PrinterJob pj = PrinterJob.getPrinterJob();
        if(pj.printDialog()) {
            JEditorPane text = new JEditorPane("text/html", "text");
//            text.setText("Return this page to Shyarmal.");
   BufferedReader(new InputStreamReader(new FileInputStream(new File("a.html")))), "");
            pj.setPrintable(text.getPrintable(head, foot));
            System.out.println("done .............. ");


First a PrinterJob instance is obtained.
          PrinterJob pj = PrinterJob.getPrinterJob();

Then a panel will be popped to take a user input.  It's done by the code segment, 'pj.printDialog()', which returns true if the user chooses to print and false otherwise.

Then a JEditorPane instance is formed specifying the content type and an initial text.
         JEditorPane text = new JEditorPane("text/html", "text");
An alternative way to do the same is;
        JEditorPane text = new JEditorPane();

The content should be set to the JEditorPane for printing.
Text can either be set like
       'text.setText("Return this page to Shyarmal.");'
or read from a file as done in the example
[ BufferedReader(new InputStreamReader(new FileInputStream(new File("a.html")))), ""); ]

Then repaint method should be called on the JEditorPane for the changes to it be updated.

'pj.setPrintable(text.getPrintable(head, foot))' sets the JEditorPane for printing.
The print() method of PrinterJob, does the printing.



  1. Thaank u so really helped me

  2. More helpful than most I have found. Thanks!

    I am still having problems getting the output to size to the printed page. I'm getting there a little bit at a time.

  3. This comment has been removed by the author.