java - 使用 Printable on Java 打印多页

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

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

有人可以帮助我吗?

最佳答案

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

关于java - 使用 Printable on Java 打印多页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152261/

相关文章:

java - 在Java线程应用程序中获取不正确的输出? [复制]

Android 项目从 Eclipse 中消失

eclipse 启动插件安装非常慢

c - 如何计算至少包含 3 个元音的单词数

java - 如果是,如何让我的程序循环程序,如果否,则退出程序并打印

java - 将一个变量分配给另一个变量的速度

java - 是否必须有 doGet 或 doPost 方法?

java - Spring JPA Data Repository 通用实现示例

java - Windows 10 中未返回默认打印机

ios - 从 swift uiwebview 打印