/Users/lyon/j4p/src/addBk/print/PrintUtils.java
|
1 /*
2 * Created by DocJava, Inc.
3 * User: lyon
4 * Date: Mar 2, 2003
5 * Time: 12:30:51 PM
6 */
7 package addBk.print;
8
9 import java.awt.*;
10 import java.awt.print.PageFormat;
11 import java.awt.print.Printable;
12 import java.awt.print.PrinterException;
13 import java.awt.print.PrinterJob;
14 import java.io.RandomAccessFile;
15
16 public class PrintUtils implements Printable {
17 private RandomAccessFile raf;
18 private String fileName;
19 private Font fnt = new Font("Helvetica", Font.PLAIN, 10);
20 private int rememberedPageIndex = -1;
21 private long rememberedFilePointer = -1;
22 private boolean rememberedEOF = false;
23
24 public PrintUtils(String file) {
25 fileName = file;
26 try {
27 // Open file
28 raf = new RandomAccessFile(file, "r");
29 } catch (Exception e) {
30 rememberedEOF = true;
31 }
32 }
33
34 public PrintUtils() {
35 this(futils.Futil.getReadFileName("select a file to print"));
36 }
37
38 public static void printFile() {
39 PrinterJob job = PrinterJob.getPrinterJob();
40 // Specify the Printable is an instance of SimplePrint
41 job.setPrintable(new PrintUtils());
42 // Put up the dialog box
43 if (job.printDialog()) {
44 // Print the job if the user didn't cancel printing
45 try {
46 job.print();
47 } catch (Exception e) { /* handle exception */
48 e.printStackTrace();
49 }
50 }
51 System.exit(0);
52 }
53
54
55 public int print(Graphics g, PageFormat pf, int pageIndex)
56 throws PrinterException {
57 try {
58 // For catching IOException
59 if (pageIndex != rememberedPageIndex) {
60 // First time we've visited this page
61 rememberedPageIndex = pageIndex;
62 // If encountered EOF on previous page, done
63 if (rememberedEOF) return Printable.NO_SUCH_PAGE;
64 // Save current position in input file
65 rememberedFilePointer = raf.getFilePointer();
66 } else
67 raf.seek(rememberedFilePointer);
68 g.setColor(Color.black);
69 g.setFont(fnt);
70 int x = (int) pf.getImageableX() + 10;
71 int y = (int) pf.getImageableY() + 12;
72 // Title line
73 g.drawString("File: " + fileName + ", page: " +
74 (pageIndex + 1), x, y);
75 // Generate as many lines as will fit in imageable area
76 y += 36;
77 while (y + 12 < pf.getImageableY() + pf.getImageableHeight()) {
78 String line = raf.readLine();
79 if (line == null) {
80 rememberedEOF = true;
81 break;
82 }
83 g.drawString(line, x, y);
84 y += 12;
85 }
86 return Printable.PAGE_EXISTS;
87 } catch (Exception e) {
88 return Printable.NO_SUCH_PAGE;
89 }
90 }
91
92 }
93
94