附加用于打印JTable前后的文本

时间:2021-08-31 12:05:56

I am trying to print a JTable and the print() method works great till I come to this scenario. Lets say I want to print before, in the first page only (not header) the text "Report" and on the end the text "This is the end of report". I would like once more to clarify that I don't need a header or footer only this text to appear in the top of the first and bottom of the last page when I print them.

我正在尝试打印一个JTable,而print()方法在我进入这个场景之前工作得很好。假设我想要在第一页(而不是页眉)之前打印文本“报告”,在最后打印文本“这是报告的结尾”。我想再次澄清,我不需要页眉或页脚,只需要这个文本在打印时出现在最后一页的顶部和底部。

How can I do this?

我该怎么做呢?

1 个解决方案

#1


4  

One way to do this is to append() a series of suitable Printable instances to a java.awt.print.Book, as shown here.

一种方法是将一系列合适的可打印实例添加到java.awt.print中。书,如下所示。

Addendum: JTable has a getPrintable() method that should simplify things; here's an outline and simple title Printable:

附录:JTable有一个getPrintable()方法,可以简化事情;这里有一个大纲和简单的标题:

PrinterJob pj = PrinterJob.getPrinterJob();
Book book = new Book();
book.append(new Title(), pj.defaultPage());
book.append(table.getPrintable(...), pj.defaultPage());
book.append(new EndPage(), pj.defaultPage());
pj.setPageable(book);
pj.print();
...
private static class Title implements Printable {

    Font font = new Font("SansSerif", Font.PLAIN, 48);

    @Override
    public int print(Graphics g, PageFormat pf, int pageIndex)
        throws PrinterException {
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        g2d.setFont(font);
        g2d.setColor(Color.black);
        g2d.drawString("Report", 50, 200);
        return Printable.PAGE_EXISTS;
    }
}

#1


4  

One way to do this is to append() a series of suitable Printable instances to a java.awt.print.Book, as shown here.

一种方法是将一系列合适的可打印实例添加到java.awt.print中。书,如下所示。

Addendum: JTable has a getPrintable() method that should simplify things; here's an outline and simple title Printable:

附录:JTable有一个getPrintable()方法,可以简化事情;这里有一个大纲和简单的标题:

PrinterJob pj = PrinterJob.getPrinterJob();
Book book = new Book();
book.append(new Title(), pj.defaultPage());
book.append(table.getPrintable(...), pj.defaultPage());
book.append(new EndPage(), pj.defaultPage());
pj.setPageable(book);
pj.print();
...
private static class Title implements Printable {

    Font font = new Font("SansSerif", Font.PLAIN, 48);

    @Override
    public int print(Graphics g, PageFormat pf, int pageIndex)
        throws PrinterException {
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        g2d.setFont(font);
        g2d.setColor(Color.black);
        g2d.drawString("Report", 50, 200);
        return Printable.PAGE_EXISTS;
    }
}