===================================================================
package ds.demo.service;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
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.");
text.read(new BufferedReader(new InputStreamReader(new FileInputStream(new File("a.html")))), "");
text.repaint();
pj.setPrintable(text.getPrintable(head, foot));
pj.print();
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();
text.setContentType("text/html");
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
[ text.read(new 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.
thanks,
Shyarmal.
Thaank u so much...it really helped me
ReplyDeleteYou are welcome ..... :)
DeleteMore helpful than most I have found. Thanks!
ReplyDeleteI am still having problems getting the output to size to the printed page. I'm getting there a little bit at a time.
This comment has been removed by the author.
ReplyDeleteGreat article
ReplyDelete