Java Printing
Hi,
can anybody help on the following:
I would like to print (on a printer device) using the Java (Swing) Printing API; I found several examples which all consider to print the content of an external file... I need to print from a Java Object, printing line by line basically. I though I could render the content of the Object by overriding toString(). It doesn't seem to work in this way :(
Any idea, reference, example to submit?
Thanks in advance!
paolo
[494 byte] By [
S.O.S.a] at [2007-11-27 5:05:35]

# 2
I think you want to print text.
The example below prints three lines of text on a page.
It creates a Book bk.
It calls bk.append(.,.) once, to add one page.
To print more than one page, append more pages.
Pass different Printable's, or pass the same Printable and let it check the pageIndex argument.
import java.awt.Font;
import java.awt.Graphics;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
public class ReportWriter
{
public static void print()
throws PrinterException
{
print(new PagePainter());
}
private static void print(Printable pagePainter)
throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = job.defaultPage();
Book bk = new Book();
bk.append(pagePainter, job.defaultPage());
job.setPageable(bk);
if (job.printDialog())
job.print();
}
private static class PagePainter implements Printable
{
static final Font fontHeader = new Font("Sans serif", Font.PLAIN, 13);
static final Font fontNormal = new Font("Serif", Font.PLAIN, 11);
static final int spacingHeader = 20;
static final int spacingNormal = 14;
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException
{
int top = (int) g.getClipBounds().getMinY();
int left = (int) g.getClipBounds().getMinX();
int y = top;
g.setFont(fontHeader);
g.drawString("HEADER", left, y);
y += spacingHeader;
g.setFont(fontNormal);
g.drawString("line1", left, y);
y += spacingNormal;
g.drawString("line2", left, y);
y += spacingNormal;
return Printable.PAGE_EXISTS;
}
}
}