1

I need to print images in Java. So I implemented print() method of Printable interface. But printer always prints only some piece of original image. How I can cause image to fit printing area (A4), so printer be able to print whole image, not piece of them? Now my code looks like this:

public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {


    if (pageIndex >= images.size()) {
        return Printable.NO_SUCH_PAGE;
    }
    RenderedImage image;


    Graphics2D graphics2D = (Graphics2D) graphics;

    image = new NullOpImage((RenderedImage) images.get(pageIndex), null, null, OpImage.OP_IO_BOUND);


    double x = (pageFormat.getImageableWidth() - image.getWidth())/2 + pageFormat.getImageableX();
    double y = (pageFormat.getImageableHeight() - image.getHeight())/2 + pageFormat.getImageableY();


    graphics2D.drawRenderedImage(image, AffineTransform.getTranslateInstance(x, y));

    return PAGE_EXISTS;
}
Adil
  • 4,503
  • 10
  • 46
  • 63
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286

1 Answers1

3

You need to scale the image down to fit the available area.

private int currentPage = -1;
private Image cachedScaledImage = null;

public double getScaleFactor(int iMasterSize, int iTargetSize) {
    double dScale = 1;
    if (iMasterSize > iTargetSize) {
        dScale = (double) iTargetSize / (double) iMasterSize;
    } else {
        dScale = (double) iTargetSize / (double) iMasterSize;
    }
    return dScale;
}

public double getScaleFactorToFit(BufferedImage img, Dimension size) {
    double dScale = 1;
    if (img != null) {
        int imageWidth = img.getWidth();
        int imageHeight = img.getHeight();
        dScale = getScaleFactorToFit(new Dimension(imageWidth, imageHeight), size);
    }
    return dScale;
}

public double getScaleFactorToFit(Dimension original, Dimension toFit) {
    double dScale = 1d;
    if (original != null && toFit != null) {
        double dScaleWidth = getScaleFactor(original.width, toFit.width);
        double dScaleHeight = getScaleFactor(original.height, toFit.height);

        dScale = Math.min(dScaleHeight, dScaleWidth);
    }
    return dScale;
}

public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {

    if (pageIndex >= images.size()) {
        return Printable.NO_SUCH_PAGE;
    }
    RenderedImage image;


    Graphics2D graphics2D = (Graphics2D) graphics;

    int width = (int)Math.round(pageFormat.getImageableWidth());
    int height = (int)Math.round(pageFormat.getImageableHeight());

    if (currentPage != pageIndex || cachedScaledImage == null) {
        currentPage = pageIndx;    

        image = new NullOpImage((RenderedImage) images.get(pageIndex), null, null, OpImage.OP_IO_BOUND);

        BufferedImage imageCopy = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = imageCopy.createGraphics();
        g2d.drawImage(imageCopy, 0, 0, null);
        g2d.dispose();

        double scaleFactor = getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), new Dimension(width, height));

        int imageWidth = (int)Math.round(image.getWidth() * scaleFactor);
        int imageHeight = (int)Math.round(image.getHeight() * scaleFactor);

        double x = ((pageFormat.getImageableWidth() - imageWidth) / 2) + pageFormat.getImageableX();
        double y = ((pageFormat.getImageableHeight() - imageHeight) / 2) + pageFormat.getImageableY();

        cachedScaledImage = imageCopy.getScaledInstance(imageWidth, imageHeight, Image.SCALE_SMOOTH);

    }

    graphics2D.drawRenderedImage(cachedScaledImage, AffineTransform.getTranslateInstance(x, y));

    return PAGE_EXISTS;
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • **thanks. But I got:** `ClassCastExcepion` **here:** `graphics2D.drawRenderedImage(scaledImage, AffineTransform.getTranslateInstance(x, y));` **I fixed it (by changing method) to** `drawImage(...)`. **But now I get** `Java.lang.OutOfMemoryError: Java heap space` – WelcomeTo Aug 29 '12 at 09:41
  • That's not surprising. The system many request a particular page page be rendered multiple times, meaning each time, we're creating a new copy of the image and scaled instance each time. You should look at creating a cache that would allow you to cache the scaled instance and reference that instance until the page number changes – MadProgrammer Aug 29 '12 at 09:52
  • I read that JAI-ImageIO tools may cause errors like this. Need I `NullOpImage`? Or I can change it by another class? – WelcomeTo Aug 29 '12 at 10:03
  • I've updated my code to demonstrate using a cached version of the scaled image. I'm not sure what you're trying to achieve from the `NullOpImage` so I can't suggest anything there – MadProgrammer Aug 29 '12 at 10:28
  • I don't need to use `NullOpImage`, I get it from sample... When I change `NullOpImage` to simple `java.awt.Image` i no more get error like `OutOfMemoryError`. So I think I shouldn't use `NullOpImage`. But if I use `Image`, methods like `getWidth` and `getHeight` requires additional parameter (`ImageObserver`) and when I pass `null` as parameter printed empty pages, not actual image... – WelcomeTo Aug 29 '12 at 10:43
  • All what I need is to print all images from `List` in A4 format. No more. – WelcomeTo Aug 29 '12 at 10:57
  • If you have control over the List of Images, I'd use BufferedImage over, say ImageIcon, as BufferedImage will load its image data into memory, reliving the need for an ImageObserver – MadProgrammer Aug 29 '12 at 11:04