Java Printing to specific page size using label printer

alwinc picture alwinc · Jun 8, 2012 · Viewed 12.2k times · Source

I am trying to use a label printer (EPSON TM-T88V to be specific), to spit out PNG images.

I can get it to print fine, except when I am printing an image dimensions (220x175 at 72dpi to be specific again) there is a wad of white space on top of the image printed, which I think is a waste of paper.

Any ideas on how I can minimize the paper waste? I want it to print just the image, minimal whitespace and then cut the paper.

Here is my code

    AttributeSet aset = new HashAttributeSet();
    aset.add(new PrinterName(printerName, null));
    /* locate a print service that can handle the request */
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PNG, aset);

    if (services.length >= 1) {
        /* create a print job for the chosen service */
        DocPrintJob pj = services[0].createPrintJob();

        DocAttributeSet das = new HashDocAttributeSet();
        das.add(PrintQuality.HIGH);
        das.add(MediaSizeName.ISO_A7); // I know the problem is here somewhere. This Media size seems to work best currently

        try {
            /* 
            * Create a Doc object to hold the print data.
            */
            Doc doc = new SimpleDoc(imageByteIs, DocFlavor.INPUT_STREAM.PNG, das);

            /* print the doc as specified */
            pj.print(doc, null);

        } catch (PrintException e) { 
            System.err.println(e);
        }
    }

Answer

Some Java Programmer picture Some Java Programmer · Apr 22, 2013

You can find the available paper sizes via:

PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
Media[] res = (Media[]) printService.getSupportedAttributeValues(Media.class, null, null);
for (Media media : res) {
    if (media instanceof MediaSizeName) {
        MediaSizeName msn = (MediaSizeName) media;
        MediaSize ms = MediaSize.getMediaSizeForName(msn);
        float width = ms.getX(MediaSize.INCH);
        float height = ms.getY(MediaSize.INCH);
        System.out.println(media + ": width = " + width + "; height = " + height);
    }
}

Once you've found the available MediaSizeName that most closely fits your paper size, simply add it in place of MediaSizeName.ISO_A7.