Getting access to all printers configured in machine

This post explains how to programmatically get access to all printers configured in a machine. Java provides lookup facitlity through PrintServiceLookup class. This class has static methods through which we can get a reference to all the printers.

We use the lookupPrintServices method in the PrintServiceLookup class. The api definition is as shown below

public static final PrintService[] lookupPrintServices(DocFlavor flavor, AttributeSet attributes)

where
DocFlavor contains the mime type of any document to be printed and the source of the document. The source can be byte array, inputstream, reader etc
AttributeSet contains a collection of printer attributes supplied by client to get the list of printer matching the supplied printer attributes.

The return value of the method will be a list of PrintService instances which matches the client provided docFlavor and printer attributes.

Since we need access to all the printers we pass null to both arguments.

The below code gets reference to all the configured printer in a machine and print the supported mime types and the source type (the source from which the printer reads)

Main Class


package Printing;

import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;

public class PrintingDemo2 {
    public static void main(String[] args) {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        for(int i = 0; i < services.length; i++) {
            System.out.println(services[i].getName());
            DocFlavor[] docFlavors = services[i].getSupportedDocFlavors();
            for(DocFlavor docFlavor : docFlavors) {
                System.out.println("\t" + docFlavor.toString());
            }
            System.out.println("");
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s