tags:

views:

398

answers:

1

Hello, I am creating one GUI in swing Java. I have to use one button " Print " which will directly start printing the file I have set without opening the default Print dialog box. I have to check first whether printner is attached to my computer or not ?

A: 

May be using PrintServiceLookup?

Implementations of this class provide lookup services for print services (typically equivalent to printers) of a particular type.

DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
    DocPrintJob pj = pservices[0].createPrintJob();
    //....
}

Note: the number of PrintService should be at least one iff there is a printer. Potentially at least 2 if there is an actual printer, since you can have pure software printers installed on your computer. See also this thread.

Depending on the platform and jdk, it can have some bug, but otherwise, the following method is supposed to at least list the printers:

import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.text.*;
import javax.print.attribute.standard.*;

public class ShowPrinters {

    public ShowPrinters() {
    }

    public static void main(String[] args) {
        DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset);
        System.out.println("The following printers are available");
        for (int i=0;i<services.length;i++) {
            System.out.println("  service name: "+services[i].getName());
        }
    }
}


In this eclipse code source, you have see the use of PrinterState to check if the printer is actually connected:

AttributeSet attributes = new HashPrintServiceAttributeSet(
    new PrinterName(printerName, Locale.getDefault()));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
    DocFlavor.SERVICE_FORMATTED.PRINTABLE,
    attributes);
PrintService printService = services[0];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);

Check if printerState is not null. Note: this might not be always enough (see this thread).

VonC
Yes, I am getting the name of printer here,but my printer is not physically attached to my computer.How should I check it first before proceeding ?
om
I would think that as long as the printer has been "installed" on the box it should be available via the above code whether it is a local or network printer. I would test it out but I dont have either option available at the moment. :-)
cjstehno