Search code examples
javaprintingscalerescale

Rescale an image for printing


I need to rescale an image for printing, but I only have two different results:

  • The image is bigger than the page.
  • The image is cutted and I see only a small percent of the image on the page.

I put two images to see it better. The first one is the result that I have now:

enter image description here

And the second one is the image that I have to see on the page, I have to rescale because is bigger than the page:

enter image description here

It could be a print problem or the method "rescale" does not works? I put my code below:

public int print(Graphics g, PageFormat pf, int pageIndex) 
          {
            if (pageIndex != 0)
              return NO_SUCH_PAGE;
            Graphics2D g2 = (Graphics2D) g;
            g2.setFont(new Font("Serif", Font.PLAIN, 36));
            g2.setPaint(Color.black);
            g2.scale(200, 200);                 
            g2.drawImage(createImage(temperaturePlot), null, 20, 20);
            return PAGE_EXISTS;
          }

    public BufferedImage createImage(JPanel panel) 
   {
   int w = panel.getWidth();
   int h = panel.getHeight();
   BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
   Graphics2D g = bi.createGraphics();
   panel.paint(g);

   return bi;       
   }

All I want is to scale the image and see all the values on the page.

Any help? Thanks!

I change the method with the new commens, but it doesn't work:

class MyPrintableGraphic implements Printable 
        {
          public int print(Graphics g, PageFormat pf, int pageIndex) 
          {
            if (pageIndex != 0)
              return NO_SUCH_PAGE;

            BufferedImage original = createImage(temperaturePlot);

            original.getScaledInstance(200, 200,BufferedImage.SCALE_DEFAULT);

            Graphics2D g2 = (Graphics2D) g;
            g2.setFont(new Font("Serif", Font.PLAIN, 36));
            g2.setPaint(Color.black);
            //BufferedImage image = createImage(temperaturePlot); 
            //Image scaled = image.getScaledInstance(200,200,Image.SCALE_SMOOTH); 
            g2.drawImage(original, 0, 0, null);
            /*BufferedImage mbi = resizeImage(createImage(temperaturePlot), 200, 200);
            g2.drawImage(mbi, null, 20, 20);*/
            return PAGE_EXISTS;
          }
        }

Here is the new fail result:

enter image description here


Solution

  • Try with that:

    g2.drawImage(createImage(temperaturePlot).getScaledInstance(500, 300,BufferedImage.SCALE_SMOOTH), 85, 65, null);
    

    I think this solve your problem.