Hi there,
Can somebody help me to make my text to be printer by the printer in a nice
pattern. Now I am using this code:
-------------------------------------------------------------------------------------------
class B{
PrinterJob printerJob = PrinterJob.getPrinterJob();
Book book = new Book();
book.append(new PrintReceipt(), new PageFormat());
printerJob.setPageable(book);
boolean doPrint = printerJob.printDialog();
if (doPrint)
{
try
{
printerJob.print();
}
catch (PrinterException exception)
{
System.err.println("Printing error: " + exception);
}
}
public class PrintReceipt implements Printable
{
private static
String TEXT = "my name: \n\txx\n\tmy age:xx";
private static AttributedString mStyledText= new AttributedString(TEXT);
public int print(Graphics g, PageFormat format, int pageIndex)
{
Graphics2D g2d = (Graphics2D) g;
g2d.translate(format.getImageableX(), format.getImageableY());
g2d.setPaint(Color.black);
Point2D.Float pen = new Point2D.Float();
AttributedCharacterIterator charIterator = mStyledText.getIterator();
LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
float wrappingWidth = (float) format.getImageableWidth();
while (measurer.getPosition() < charIterator.getEndIndex())
{
TextLayout layout = measurer.nextLayout(wrappingWidth);
pen.y += layout.getAscent();
float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
layout.draw(g2d, pen.x + dx, pen.y);
pen.y += layout.getDescent() + layout.getLeading();
}
return Printable.PAGE_EXISTS;
}
}
---------------------------------------------------------------------------------------
Even by using carriage return and tab(\n, \t) they have no effect on the printed text; they appear on the printer document as one
word next to the other.