Java打印的重试?

时间:2010-08-12 22:19:38

标签: java printing

如果您运行以下代码(来自here),则会调用两个页面:

class PrintObject implements Printable
{
    public int print (Graphics g, PageFormat f, int pageIndex)
    {
        System.out.println("Page "+pageIndex);
        Graphics2D g2 = (Graphics2D) g; // Allow use of Java 2 graphics on
        // the print pages :

        // A rectangle that shows the printable area of the page, allowing
        // for margins all round. To be drawn on the first page (index = 0).
        Rectangle2D rect = new Rectangle2D.Double(f.getImageableX(),
        f.getImageableY(),
        f.getImageableWidth(),
        f.getImageableHeight());

        // A simple circle to go on the second page (index = 1).
        Ellipse2D circle = new Ellipse2D.Double(100,100,100,100);

        switch (pageIndex)
        {
            case 0 : g2.setColor(Color.black); // Page 1 : print a rectangle
                g2.draw(rect);
                return PAGE_EXISTS;
            case 1 : g2.setColor(Color.red); // Page 2 : print a circle
                g2.draw(circle);
                return PAGE_EXISTS;
            default: return NO_SUCH_PAGE; // No other pages
        }
    }


    public static void main (String[] args)
    {
        // Create an object that will hold all print parameters, such as
        // page size, printer resolution. In addition, it manages the print
        // process (job).
        PrinterJob job = PrinterJob.getPrinterJob();

        // It is first called to tell it what object will print each page.
        job.setPrintable(new PrintObject());

        // Then it is called to display the standard print options dialog.
        if (job.printDialog())
        {
        // If the user has pressed OK (printDialog returns true), then go
        // ahead with the printing. This is started by the simple call to
        // the job print() method. When it runs, it calls the page print
        // object for page index 0. Then page index 1, 2, and so on
        // until NO_SUCH_PAGE is returned.
        try { job.print(); }
        catch (PrinterException e) { System.out.println(e); }
        }
    }
}

我不知道为什么它会在如此简单的情况下执行此操作,但真正的问题是我们有代码打印大JTable,并且在成功之前重试打印超过500次。即使对于相对较小的JTable,它也会重试11次。我们正在使用java.awt.print.PrintJob,关闭双缓冲并使用CutePDF在具有2G RAM和1G堆(-Xmx1000m)的机器上进行测试

有谁知道会导致如此多的重试?

1 个答案:

答案 0 :(得分:0)

我假设你在谈论每个页面调用print(...)方法的频率。

不幸的是,没有真正的方法可以知道它将被调用多少次,更不用说控制它了,因为它是你系统的JVM的打印子系统。

您所能做的就是尽力优化绘图程序,因为它可以被多次调用(甚至过度调用)。

您也应该查看Graphic2D clipBounds,它可能会告诉您正在打印整个页面的哪个子集。

在我的简单测试中,在Mac上,使用您的代码,每个页面调用两次print。一旦看起来像是用于了解你要打印什么的图形,然后再使用实际系统Graphics2D进行实际渲染。