printing long text as paragraph
authorBill Erickson <berick@esilibrary.com>
Wed, 26 Feb 2014 03:12:49 +0000 (22:12 -0500)
committerBill Erickson <berick@esilibrary.com>
Wed, 26 Feb 2014 03:12:49 +0000 (22:12 -0500)
Signed-off-by: Bill Erickson <berick@esilibrary.com>
src/org/evergreen_ils/hatch/PrintDriver.java

index 79a013a..316814b 100644 (file)
@@ -13,11 +13,21 @@ import javax.print.PrintServiceLookup;
 import javax.print.attribute.Attribute;
 import javax.print.attribute.AttributeSet;
 
+import java.awt.font.FontRenderContext;
+import java.awt.font.LineBreakMeasurer;
+import java.awt.font.TextAttribute;
+import java.awt.font.TextLayout;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.text.AttributedString;
+
 public class PrintDriver implements Printable {
 
     private String printText;
     private static final Logger logger = Log.getLogger("PrintDriver");
 
+    private final static int POINTS_PER_INCH = 72;
+
     public int print(Graphics g, PageFormat pf, int page) 
         throws PrinterException {
 
@@ -28,10 +38,41 @@ public class PrintDriver implements Printable {
         Graphics2D g2d = (Graphics2D)g;
         g2d.translate(pf.getImageableX(), pf.getImageableY());
 
+        /* --------------------------------------------- */
+        /* -- rendering the print text as paragraph ---  */
+        Point2D.Double pen = new Point2D.Double(
+            0.25 * POINTS_PER_INCH, 0.25 * POINTS_PER_INCH);
+        double width = 7.5 * POINTS_PER_INCH;
+        AttributedString paragraphText = new AttributedString(printText);
+
+        LineBreakMeasurer lineBreaker = new LineBreakMeasurer(
+             paragraphText.getIterator(), new FontRenderContext(null, true, true));
+
+        //--- Create the TextLayout object
+        TextLayout layout;
+
+        //--- LineBreakMeasurer will wrap each line to correct length and
+        //--- return it as a TextLayout object
+        while ((layout = lineBreaker.nextLayout((float) width)) != null) {
+            //--- Align the Y pen to the ascend of the font, remember that
+            //--- the ascend is origin (0, 0) of a font. Refer to figure 1
+            pen.y += layout.getAscent();
+
+            //--- Draw the line of text
+            layout.draw(g2d, (float) pen.x, (float) pen.y);
+
+            //--- Move the pen to the next position adding the descent and
+            //--- the leading of the font
+            pen.y += layout.getDescent() + layout.getLeading();
+        }
+        /* -------------------------------------------- */
+
+        /*
         int x = 5;
         int y = 5;
         for (String line : printText.split("\n"))
             g.drawString(line, x, y += g.getFontMetrics().getHeight());
+        */
 
         return PAGE_EXISTS;
     }