Printing with Attributes(Tray Control, Duplex, etc…) using javax.print library

后端 未结 5 846
一个人的身影
一个人的身影 2020-12-02 20:36

I\'ve been trying for some time to determine a way to use the standard Java Print library to print files - specifically, PDF documents - with certai

5条回答
  •  没有蜡笔的小新
    2020-12-02 21:24

    I've found the trick for the printer trays is to iterate over the Media.class using getSupportedAttributeValues(...), match the human-readable name, and select that particular value. Tested on Windows, MacOS with several tray configurations.

    String tray = "1";
    
    // Handle human-readable names, see PRINTER_TRAY_ALIASES usage below for context.  Adjust as needed.
    List PRINTER_TRAY_ALIASES = Arrays.asList("", "Tray ", "Paper Cassette ");
    
    // Get default printer
    PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
    
    // Attributes to be provided at print time
    PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
    
    Media[] supported = printService.getSupportedAttributeValues(Media.class, null, null);
    for(Media m : supported) {           
        for(String pta : PRINTER_TRAY_ALIASES) {
            // Matches "1", "Tray 1", or "Paper Cassette 1"
            if (m.toString().trim().equalsIgnoreCase(pta + tray)) {
                attributes.add(m);
                break;
            }
        }
    }
    
    // Print, etc
    // printJob.print(pdfDoc, pset);
    

提交回复
热议问题