让图片居中

static class ImagePrintable implements Printable {
    private BufferedImage image;

    ImagePrintable(PrinterJob printJob, BufferedImage image) {
        this.image = image;
    }

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex != 0) {
            return NO_SUCH_PAGE;
        }
        Graphics2D g2d = (Graphics2D) g;
        
        double pageWidth = pageFormat.getImageableWidth();
        double pageHeight = pageFormat.getImageableHeight();
        double imageWidth = image.getWidth();
        double imageHeight = image.getHeight();
        double scaleX = pageWidth / imageWidth;
        double scaleY = pageHeight / imageHeight;
        double scaleFactor = Math.min(scaleX, scaleY);

        // Computes the x and y coordinates where to draw the image on the page
        double x = (pageWidth - imageWidth * scaleFactor) / 2;
        double y = (pageHeight - imageHeight * scaleFactor) / 2;

        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        g2d.drawImage(image, (int) x, (int) y, (int) (imageWidth * scaleFactor), (int) (imageHeight * scaleFactor), null);
        return PAGE_EXISTS;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30346433/article/details/132796947
今日推荐