Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Invoking printer using java

Ramkumar Vaitheki
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
Hi all,

Please skim through this code,

import java.awt.print.*;
import java.text.*;

public class PrintText implements Printable {

private static final String mText ="Device Name: "+acmtxt_DeviceName.getText()+"\n Alarm Text :"++acmtxt_AlarmText.getText()+"\n Time stamp: "+acmtxt_TimeStamp.getText()+"\n Alarm Detail: "+jta_AlarmDetail.getText();

private static final AttributedString mStyledText = new AttributedString(mText);

static public void main(String args[]) {

PrinterJob printerJob = PrinterJob.getPrinterJob();

Book book = new Book();
book.append(new PrintText(), new PageFormat());


boolean doPrint = printerJob.printDialog();
if (doPrint) {
try {
} catch (PrinterException exception) {
System.err.println("Printing error: " + exception);
public int print(Graphics g, PageFormat format, int pageIndex) {

Graphics2D g2d = (Graphics2D) g;

g2d.translate(format.getImageableX(), format.getImageableY());


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;

Please skim through the above code. It does well of printing, the only issue was it does not print what i has inputted text. Rather than it prints sequentially. Anyone can help me out in this regard to print this as this form

Device Name: N/A
Alarm Text: New Device Found.
Time Stamp: 2007-09-01 19:57:56
Alarm Detail: New Device Found. IP Address:

Now it prints as Device Name: N/AAlarm Text: New Device Found.Time Stamp: 2007-09-01 19:57:56Alarm Detail: New Device Found. IP Address:

Any one please help me out, immediate reply it would be helpful..

Thanks in advance,
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic