论坛首页 入门技术论坛

Java打印-Print Swing component

浏览 3104 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-01-07  
Java打印
使用 PrintRequestAttributeSet 控制页面大小和方向



private void printComp() throws HeadlessException {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        pras.add(javax.print.attribute.standard.MediaSizeName.ISO_A4);
        pras.add(javax.print.attribute.standard.OrientationRequested.LANDSCAPE);

        if (printJob.printDialog(pras)) {
            try {
                printJob.setPrintable(this, printJob.getPageFormat(pras));
                printJob.print();
            } catch (PrinterException pe) {
                System.out.println("Error printing: " + pe);
            }
        }

    }

@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex > 0) {
            return (NO_SUCH_PAGE);
        } else {
            Graphics2D g2d = (Graphics2D) graphics;
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
            double d = pageFormat.getImageableWidth() / bp.getWidth();
            g2d.scale(d, d);
            // Turn off double buffering
            disableDoubleBuffering(this.bp);
            content.paint(g2d);
            // Turn double buffering back on
            enableDoubleBuffering(this.bp);
            return (PAGE_EXISTS);
        }

}


论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics