【问题标题】:Print more than one page with Printable on Java使用 Printable on Java 打印多页
【发布时间】:2015-01-26 14:39:26
【问题描述】:

我需要在我的应用程序上打印多页,但是当我尝试打印它时,我只打印了一页,或者同一页打印了 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”条件,我会打印更多页面,但所有页面都使用相同的文本。

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

有人可以帮我吗?

【问题讨论】:

  • 为什么不用pageIndex来选择要打印的数据呢?见Printing a Multiple Page Document
  • 我在两个小时前看到了,但我不知道如何在我的代码上使用它,您能帮帮我吗?
  • 您需要确定哪些数据属于哪个页面,并相应地修改您的for循环。可能类似于for(int i = pageIndex * linesPerPage; i &lt; sTable.size() &amp;&amp; i &lt; (pageIndex+1)*linesPerPage; i++),其中linesPerPage 是您计划在每页上显示的表格条目数。

标签: java eclipse printing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多