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 {
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;
}