Print text File to specific printer in java

后端 未结 2 1353
渐次进展
渐次进展 2020-12-14 05:06

I have a text file, and I need to print it to a specific network printer. I know the name of the printer.

Until now I have made a Printable class to print my file (t

相关标签:
2条回答
  • 2020-12-14 05:39

    JTextComponent#print should do the trick:

    JTextPane jtp = new JTextPane();
    jtp.setBackground(Color.white);
    jtp.setText("text to print");
    boolean show = true;
    try {
        jtp.print(null, null, show, null, null, show);
    } catch (java.awt.print.PrinterException ex) {
        ex.printStackTrace();
    }
    

    in this manner you can quickly print out even nice formatted text - just create a StyledDocument and attach it to JTextPane before printing.

    0 讨论(0)
  • 2020-12-14 05:54

    I'm not sure if this solves your problem but I use the following to print a text file

    FileInputStream textStream;
    textStream = new FileInputStream(FILE_NAME);
    
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc mydoc = new SimpleDoc(textStream, flavor, null);
    
       PrintService[] services = PrintServiceLookup.lookupPrintServices(
                    flavor, aset);
       PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    
       if(services.length == 0) {
           if(defaultService == null) {
                 //no printer found
    
           } else {
                //print using default
                DocPrintJob job = defaultService.createPrintJob();
                job.print(mydoc, aset);
    
           }
    
        } else {
    
           //built in UI for printing you may not use this
           PrintService service = ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, aset);
    
    
            if (service != null)
            {
               DocPrintJob job = service.createPrintJob();
               job.print(mydoc, aset);
            }
    
        }
    

    You may not need the ServiceUI, but I think you could use PrintService[] services to get a list of printers available for printing. And using an input stream and the Doc class you can print a file to a printer.

    0 讨论(0)
提交回复
热议问题