 |
2. (Sect. 8) How do I print from a Java program?
[*] Use the Toolkit.getPrintJob() method
Component c = this.getParent();
while (c!=null && !(c instanceof Frame))
c=c.getParent();
// With a JComponent use c=getTopLevelAncestor();
PrintJob pj = getToolkit().getPrintJob((Frame) c, "test", null);
Graphics pg = pj.getGraphics();
printAll(pg);
pg.dispose();
pj.end();
This feature was introduced with JDK 1.1. A common place to put
this is in the code that handles a button press. Printing from an
untrusted applet is subject to a check from the SecurityManager.
The JDK 1.1 printing API is more a screen hardcopy facility than a
full blown publishing and illustration hardcopy API. JDK 1.2
offers a more full-featured printing API.
If you simply want to print text, then write it to a file and
print the file. Or open a filename that corresponds to the
printer. On Windows, that is "LPT1" and the code looks like:
try {
FileOutputStream fos = new FileOutputStream("LPT1");
PrintStream ps = new PrintStream(fos);
ps.print("Your string goes here");
ps.print("\f");
ps.close();
} catch (Exception e) {
System.out.println("Exception occurred: " + e);
}
The final formfeed is needed by windows to start the printjob.
3. (Sect. 8) What are the properties that can be used in a PrintJob?
[*] The properties are
+ awt.print.destination - can be "printer" or "file"
+ awt.print.printer - printer name
+ awt.print.fileName - name of the file to print
+ awt.print.numCopies - obvious
+ awt.print.options - options to pass to the print command
+ awt.print.orientation - can be "portrait" or "landscape"
+ awt.print.paperSize - can be "letter","legal","executive" or
"a4"
The defaults are destination=printer, orientation=portrait,
paperSize=letter, and numCopies=1.
You can search for info like this by joining the Java Developer
Connection (it's free) at http://java.sun.com/jdc.
and doing a search for "PrintJob".
 |
 |
|