Direct printing in Java

1

During execution, the below error is displayed when sending a string to printer.

sun.print.PrintJobFlavorException: invalid flavor
at sun.print.Win32PrintJob.print(Unknown Source)

Complete code

    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

    PrintService printService = printServices[5];
    System.out.println(printService.getName());
    DocFlavor docFlavor = DocFlavor.STRING.TEXT_PLAIN;


    StringBuilder value = new StringBuilder();

    value.append("\n\n");
    value.append("\n\tRelação dos Usuários:");

    List<Usuario> usuarios = TapiocariaFacade.listarUsuario();

    int y = 70;

    for(Usuario usuario : usuarios) {

        value.append("\n\tNome: " + usuario.getSenha());
        value.append("\n\tEndereço: " + usuario.getId());
        value.append("\n\tEmail: " + usuario.getEmail());
    }
    System.out.println(value.toString());


    Doc doc = new SimpleDoc(value.toString(), docFlavor, null);

    DocPrintJob docPrintJob = printService.createPrintJob();
    try {
        docPrintJob.print(doc, null);
    } catch (PrintException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
asked by anonymous 20.05.2016 / 03:50

1 answer

2

Please enter a different type for your Flavor for compatibility

DocFlavor docFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;

You have created an array with printers but there is no available printer in position 5

PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

PrintService printService = printServices[5];

You can try with

PrintService printServices = PrintServiceLookup.lookupDefaultPrintService();

Or even

PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

if (printServices.length==0) {
    JOptionPane.showMessageDialog(null, "No Printer Selected");
        }
else if (printServices.length > 0) {
        DocPrintJob pj = printServices[0].createPrintJob();
        {

And a better suggestion

    PrintService printServices= null;
    DocFlavor docFlavor = DocFlavor.STRING.TEXT_PLAIN;
    PrintRequestAttributeSet attr_set =
            new HashPrintRequestAttributeSet();

    attr_set.add(new Copies(1));           
    attr_set.add(Sides.ONE_SIDED);
    PrintService[] service = PrintServiceLookup.lookupPrintServices(docFlavor, attr_set);

    for (int i = 0; i < printServices.length; i++) {
        System.out.println(printServices[i].getName());
        if (printServices[i].getName().equals(nomeDaSuaImpressora)) {
            ps = service[i];
        }
    }
    
20.05.2016 / 05:48