Java printing: creating a PageFormat with minimum acceptable margin

前端 未结 1 386
盖世英雄少女心
盖世英雄少女心 2021-01-04 21:23

I\'m trying to get the PageFormat correct when I print. Below is an example program that shows my dilemma: I get a different result when I use printJob.setPrintable(pr

相关标签:
1条回答
  • 2021-01-04 21:47

    Hmm. After trying a number of fruitless efforts, it looks like setting a page to zero margin and then calling PrinterJob.validatePage() seems to be the only way I can get a valid minimum-margin PageFormat:

    static private PageFormat getMinimumMarginPageFormat(PrinterJob printJob) {
        PageFormat pf0 = printJob.defaultPage();
        PageFormat pf1 = (PageFormat) pf0.clone();
        Paper p = pf0.getPaper();
        p.setImageableArea(0, 0,pf0.getWidth(), pf0.getHeight());
        pf1.setPaper(p);
        PageFormat pf2 = printJob.validatePage(pf1);
        return pf2;     
    }
    

    and then I can change doPrint() to:

    protected void doPrint(boolean useBook) {
        RectangleThingy rectangleThingy = new RectangleThingy();
        System.out.println("doPrint("+useBook+")");
        try
        {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            if (useBook)
            {
                Book book = new Book();
                book.append(rectangleThingy, getMinimumMarginPageFormat(printJob));
                printJob.setPageable(book);
            }
            else
            {
                printJob.setPrintable(rectangleThingy);        
            }
            if (printJob.printDialog())
                printJob.print();
        } 
        catch(PrinterException pe) {
            System.out.println("Error printing: " + pe);
        }
    }
    
    0 讨论(0)
提交回复
热议问题