public static BufferedImage componentToImage(Component component, Rectangle region) { BufferedImage img = new BufferedImage( component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics g = img.getGraphics(); g.setColor(component.getForeground()); g.setFont(component.getFont()); component.paintAll(g); g.dispose(); if (region == null) { return img; } return img.getSubimage(region.x, region.y, region.width, region.height); }
/** This method is required to implement the Printable interface */ public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex >= 1) { return NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) g; Dimension cs = printTarget.getSize(); g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); double imageableWidth = pageFormat.getImageableWidth(); double imageableHeight = pageFormat.getImageableHeight(); double scale = 1; if (cs.width >= imageableWidth) { scale = imageableWidth / cs.width; } g2.scale(scale, scale); // g2.translate((imageableWidth - cs.width)*scale/2, // (imageableHeight - cs.height)*scale/2); printTarget.paintAll(g2); return Printable.PAGE_EXISTS; }