Reputation: 25
I need to print more than one page on my application, but when I try to print it I get only one page printed, or the same page printed 5 times, for example.
I put the code below:
MyPrintableTable mpt = new MyPrintableTable();
PrinterJob job = PrinterJob.getPrinterJob();
//PageFormat pf = job.defaultPage();
job.setPrintable(mpt);
job.printDialog();
try
{
job.print();
}
catch (PrinterException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
"MyPrintableTable" class:
class MyPrintableTable implements Printable
{
public int print(Graphics g, PageFormat pf, int pageIndex)
{
if (pageIndex != 0)
return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 16));
g2.setPaint(Color.black);
int x = 100;
int y = 100;
for(int i = 0; i < sTable.size(); i++)
{
g2.drawString(sTable.get(i).toString(), x, y);
y += 20;
}
return PAGE_EXISTS;
}
}
If I change the "pageIndex !=0" condition, I have more pages printed, but all with the same text.
I want to print all my text, that has a three page lenght, but I only can print the first one, o print three times the first one.
Can someone help me?
Upvotes: 2
Views: 2260
Reputation: 26185
Here is a test program that demonstrates the principles I previously suggested in comments. It is based on ideas from Printing a Multiple Page Document, as well as on the code in the question. In a real program I would probably calculate linesPerPage
rather than compiling in a number.
public class Test {
public static void main(String[] args) {
MyPrintableTable mpt = new MyPrintableTable();
PrinterJob job = PrinterJob.getPrinterJob();
// PageFormat pf = job.defaultPage();
job.setPrintable(mpt);
job.printDialog();
try {
job.print();
} catch (PrinterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyPrintableTable implements Printable {
private int linesPerPage = 20;
private List<String> sTable = new ArrayList<String>();
{
for (int i = 0; i < 100; i++) {
sTable.add("Line" + i);
}
}
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex * linesPerPage >= sTable.size())
return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 16));
g2.setPaint(Color.black);
int x = 100;
int y = 100;
for (int i = linesPerPage * pageIndex; i < sTable.size()
&& i < linesPerPage * (pageIndex + 1); i++) {
g2.drawString(sTable.get(i).toString(), x, y);
y += 20;
}
return PAGE_EXISTS;
}
}
Upvotes: 1