I’m new to printing with java. First I start to print one page data and all was ok. Now I start to test how to paginate my data. I have a class that implements the printable interface and I have an int variable (curLine) to keep the number of rows I have already print and an variable lines to keep the total number I want to print finally. In public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) method when I use the graphics.drawString(…); method to draw a row I increase the value of the metric(curLine++) but in the printer I didn’t get the results I want.I think that the print methold called twice for a specific indexPage, in that two calls the data printed only one, but the curLine variable increase in the two calls too with result to “lost” rows from the output.
More specific my test class is
public class PrintTest implements Printable {
private final int marginTop = 20;
private final int marginLeft = 10;
private Font mainFont = new Font("Verdana", Font.PLAIN, 10);
private Font bigFont = new Font("Verdana", Font.PLAIN, 14);
private int lines;
private int curLine;
private boolean finish = false;
public PrintTest() {
curLine = 0;
lines = 160;
}
public static void main(String[] args) {
PrinterJob job = PrinterJob.getPrinterJob(); // Use default printer
job.printDialog();
PrintTest t = new PrintTest();
job.setPrintable(t);
try {
job.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
//if printed all rows then return no_such_page
if (finish) {
return NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) graphics;
double pageH = pageFormat.getImageableHeight();
g2.setFont(mainFont);
int t = g2.getFontMetrics().charWidth('T');
int lineH = g2.getFontMetrics().getHeight();
double curY;
g2.translate(pageFormat.getImageableX() + marginLeft,
curY = pageFormat.getImageableY() + marginTop);
while ((curY < (pageH - lineH)) && (curLine < lines)) {
g2.translate(0, lineH);
g2.drawString("Print row number #" + curLine, 0, 0);
curY += lineH;
curLine++;
}
if (curLine >= lines) {
finish = true;
}
return PAGE_EXISTS;
}
}
and you can see the output here https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0ByN6KrI39kzuMTRmZDA5NTMtOGJjZi00ZmRhLThlYWYtMzUwNzE0NTdkMjcz&hl=en&authkey=CLa-svAG
You can see that it wasn’t start from row 0
Note: this solution was originally provided by the question OP.