When printing in Java, it is only possible to specify one media attribute: either paper or tray. In theory, if you choose the tray then Java knows what paper size to use and the other way around. But in practice, this does not always work and there may be situations where you need to specify both paper size and tray. To do so, there is an undocumented internal sun class called SunAlternateMedia class that can do the trick.
Selecting only a tray when printing
private static PrintRequestAttributeSet setMediaTrayOnly(PrintService printService) { PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); Media med[] = (Media[]) printService.getSupportedAttributeValues(Media.class, null, null); for (int k = 0; k < med.length; k++) { if (med[k] instanceof MediaTray && med[k].toString().trim().contains("OnlyOne")) { // Adding the value for the paper tray pras.add(med[k]); break; } } return pras; }
Selecting only paper size when printing
private static PrintRequestAttributeSet setMediaSizeOnly(PrintService printService) { PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); if (printService.isAttributeValueSupported(MediaSizeName.ISO_A4, null, null)) { // Adding the value for page size pras.add(MediaSizeName.ISO_A4); } return pras; }
Selecting both tray and paper size using SunAlternateMedia
Disclaimer: Sun classes are usually not recommended for use and should only be considered when running in a controlled environment where the JVM and the version are fixed. Some security managers (in applet for instance) will not allow access to internal Sun classes…
private static PrintRequestAttributeSet setMediaTrayAndSize(PrintService printService) { PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); Media med[] = (Media[]) printService.getSupportedAttributeValues(Media.class, null, null); for (int k = 0; k < med.length; k++) { if (med[k] instanceof MediaTray && med[k].toString().trim().contains("OnlyOne")) { // Add the MediaTray to SunAlternateMedia SunAlternateMedia am = new SunAlternateMedia(med[k]); // Adding the SunAlternateMedia pras.add(am); break; } } if (printService.isAttributeValueSupported(MediaSizeName.ISO_A4, null, pras)) { // Adding the value for page size pras.add(MediaSizeName.ISO_A4); } return pras; } } }