有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

eclipse在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 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) 个答案

  1. # 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;
      }
    }