Search code examples
javaswingprintinggraphics2d

Making margins smaller - Java Printing


I am using this code to print on paper:

//Overriden from printable interface
public int print(Graphics g, PageFormat pageFormat, int pageIndex)
            throws PrinterException {

        if (pageIndex != 0) {
            return Printable.NO_SUCH_PAGE;
        }

        Paper a4 = new Paper();
        a4.setImageableArea(0, 0, a4.getWidth(), a4.getHeight());
        pageFormat.setPaper(a4);
        pageFormat.setOrientation(PageFormat.PORTRAIT);

        Graphics2D g2d = (Graphics2D)g;
        //g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        this.setDoubleBuffered(false);
        panel.print(g2d);
        JOptionPane.showMessageDialog(null, new ImageIcon(image));
        this.setDoubleBuffered(true);

        return Printable.PAGE_EXISTS;
    }

I am trying to reduce the size of the margins programmatically. Whatever I do, there always seems to be a large missing chunk from the image's sides (Unless I remove the margins from the print dialog - but as I said, I want to remove them programatically to automate the whole process).


Solution

  • US Letter sized paper, for example, measures 8½ x 11 inches. At 72 dots per inch, that's 612 x 792.

    On a typical printer having paper of that size selected, the PageFormat object reports the following area.

    System.out.println(pf.getImageableX() + " " + pf.getImageableY()
        + " " + pf.getImageableWidth() + " " + pf.getImageableHeight());
    
    18.0 18.0 576.0 734.0
    18.0 18.0 576.0 734.0
    

    Few consumer printers are full-bleed, so the pritable area is smaller than the paper's physical dimensions would suggest. In effect, the printer can't put ink where it can't print.