title: Resize the page to fit with the contents
body: <p>I have used the following code to print the image in java. My problem is I couldn't change the default page size. The printable area will be fit with the content. Shouldn't go beyond that. </p>
  
  <pre><code>import java.awt.Graphics;
  import java.awt.Image;
  import java.awt.print.PageFormat;
  import java.awt.print.Paper;
  import java.awt.print.Printable;
  import java.awt.print.PrinterException;
  import java.awt.print.PrinterJob;
  
  import javax.swing.ImageIcon;
  
  public class Test implements Printable{
  
  
      final static Image img = new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Koala1.jpg").getImage();
      PrinterJob printJob = PrinterJob.getPrinterJob();
      static int img_width=img.getWidth(null);
      static int img_height=img.getHeight(null);
       static PrinterJob pj = PrinterJob.getPrinterJob();
  
          public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
              if (pageIndex != 0) {
                  return NO_SUCH_PAGE;
              }
               pageFormat = pj.defaultPage();
              Paper paper = new Paper();
              paper.setSize(img_width,img_height); // Large Address Dimension
              paper.setImageableArea(20, 20, img_width, img_height);
              pageFormat.setPaper(paper);
              pageFormat.setOrientation(PageFormat.LANDSCAPE);
              g.drawImage(img, 0,0, img_width, img_height,   null);
              return PAGE_EXISTS;
          }
  
  
  
    static public void main(String args[]) throws Exception {
  
  
          pj.setPrintable(new Test());
          System.out.println("width: "+img_width +" height: "+img_height);
          if (pj.printDialog()) {
            try {
              pj.print();
            } catch (PrinterException e) {
              System.out.println(e);
            }
          }
    }
  }
  </code></pre>
  
  <p>Here what I get.</p>
  
  <p><img src="https://i.stack.imgur.com/9Q3c7.png" alt="enter image description here"></p>