使用Printable on Java打印多个页面

时间:2015-01-26 14:39:27

标签: java eclipse printing

我需要在我的应用程序上打印多个页面,但是当我尝试打印它时,我只打印了一页,或者打印了相同的页面5次。

我把代码放在下面:

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 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;
    }
}

如果我更改“pageIndex!= 0”条件,我会打印更多页面,但所有页面都相同。

我想要打印我的所有文本,它有三页长度,但我只能打印第一个,打印第一个三次。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

这是一个测试程序,演示了我之前在评论中建议的原则。它基于Printing a Multiple Page Document的想法以及问题中的代码。在实际程序中,我可能会计算linesPerPage而不是编译数字。

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;
  }
}