使用 Printable on Java 打印多页

Print more than one page with Printable on Java

我需要在我的应用程序上打印不止一页,但是当我尝试打印它时,我只打印了一页,或者同一页打印了 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:

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" 条件,我会打印更多页面,但所有页面都具有相同的文本。

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

有人可以帮助我吗?

这是一个测试程序,它演示了我之前在评论中建议的原则。它基于 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;
  }
}