0
votes

I'm trying to print from differents printer trays using javax.print with no luck, I have a printer HP Officejet Pro X476dw with 2 paper trays numbered 1 and 2. My code is this:

public class ImprimeSide{
    public static void main (String [] args) {
        try {

        PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, null);

        //Acquire Printer
        PrintService printer = null;

        for(PrintService serv: pservices){
            if(serv.getName().contains("HP Officejet")){
                printer = serv;
            }
        }

        if(printer != null){

            //Open File
            FileInputStream fis = new FileInputStream("Documento2.pdf");

            //Create Doc out of file, autosense filetype
            Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);

            //Create job for printer
            DocPrintJob printJob = printer.createPrintJob();

            //Create AttributeSet
            PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();

            //Add MediaTray to AttributeSet
            pset.add(MediaTray.SIDE);

            //Print using Doc and Attributes
            printJob.print(pdfDoc, pset);

            //Close File
            fis.close();

        }

        }catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Changing the line pset.add(MediaTray.SIDE) for every constant in the class MediaTray (TOP, BOTTOM, MANUAL.. etc) doesn't change anything, it will print taking paper from the default tray.

Any sugestion will be appreciated.

1

1 Answers

0
votes

you must declare a MediaTray after mapping all media in a hashmap

       DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;

        for (PrintService service : services)
        {
            System.out.println(service);

            // we retrieve all the supported attributes of type Media
            // we can receive MediaTray, MediaSizeName, ...
            Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
            if (o != null && o.getClass().isArray())
            {
                for (Media media : (Media[]) o)
                {
                    // we collect the MediaTray available
                    if (media instanceof MediaTray)
                    {
                        System.out.println(media.getValue() + " : " + media + " - " + media.getClass().getName());
                        trayMap.put(media.getValue(), media);
                    }
                }
            }
        }

 MediaTray selectedTray = (MediaTray) trayMap.get(Integer.valueOf(mediaId));

and after you add it to the PrintRequestAttributeSet

PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
            attributes.add(selectedTray);

And when you print you use this PrintRequestAttributeSet

  DocPrintJob job = services[0].createPrintJob();
    job.print(doc, attributes);

Jorge