/Users/lyon/j4p/src/addBk/print/labels/PrintableLabel.java

1    package addBk.print.labels; 
2     
3    import java.awt.*; 
4    import java.awt.print.PageFormat; 
5    import java.awt.print.Printable; 
6    import java.awt.print.PrinterException; 
7     
8    public class PrintableLabel 
9            implements Printable { 
10       private Graphics2D g; 
11       private PageFormat fmt; 
12       private int xoff, yoff; 
13       private final int INCH = 72; 
14       private MailingLabelList labelList; 
15    
16       public PrintableLabel(MailingLabelList v) { 
17           labelList = v; 
18    
19           xoff = 18; 
20           //note the non-obvious y-offset 
21           yoff = (int) (-6.5 * INCH); 
22       } 
23    
24       //----------- 
25       //called by printing system 
26       //note that this simplistic example only prints page 0 
27       public int print(Graphics gr, PageFormat pageFormat, int page) 
28               throws PrinterException { 
29           if (page == 0) { 
30               this.fmt = pageFormat; 
31               this.g = (Graphics2D) gr; 
32    
33               printPage(); 
34               return PAGE_EXISTS; 
35           } else 
36               return NO_SUCH_PAGE; 
37       } 
38    
39       private void printPage() { 
40           MailingLabel s[] = labelList.getLabels(); 
41           for (int i = 0; i < s.length; i++) 
42               printLabel(s[i]); 
43       } 
44    
45       private void printLabel(MailingLabel label) { 
46           //draw borders in light gray 
47           g.setColor(Color.lightGray); 
48           Dimension labelSize = label.getPreferredSize(); 
49           g.drawRect(xoff, yoff, labelSize.width, labelSize.height); 
50    
51           g.setColor(Color.black); 
52    
53           String s[] = label.getLines(); 
54    
55           Font roman = new Font("Serif", Font.PLAIN, 12); 
56           g.setFont(roman); 
57           int fontHeight =  14; 
58    
59           for (int i = 0; i < s.length; i++) { 
60               int localX = xoff + INCH / 4; 
61    
62               int localY = yoff + (i+1)*fontHeight; 
63    
64               g.drawString(s[i], localX, localY); 
65    
66           } 
67           xoff += labelSize.width; 
68           if (xoff > labelSize.width*3) { 
69               xoff = 18; 
70               yoff += labelSize.height; 
71           } 
72       } 
73   } 
74