From e77ed68f3d153522a0128e98ff2c34d2d1259559 Mon Sep 17 00:00:00 2001 From: Bill Erickson Date: Tue, 25 Feb 2014 22:12:49 -0500 Subject: [PATCH] printing long text as paragraph Signed-off-by: Bill Erickson --- src/org/evergreen_ils/hatch/PrintDriver.java | 41 ++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/org/evergreen_ils/hatch/PrintDriver.java b/src/org/evergreen_ils/hatch/PrintDriver.java index 79a013ae4..316814b18 100644 --- a/src/org/evergreen_ils/hatch/PrintDriver.java +++ b/src/org/evergreen_ils/hatch/PrintDriver.java @@ -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; } -- 2.11.0