有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用java或javascript在客户端打印任何文本内容?

我有一个用Java编写的web应用程序。我需要通过选择打印机在客户端打印文本内容(而不是网页)。我可以用Java在服务器端做到这一点,但在客户端我应该如何克服呢

我应该更喜欢javascript还是小程序?我可以让解决方案在所有打印机中选择一台打印机吗

先谢谢你


共 (2) 个答案

  1. # 1 楼答案

    打印机选择在操作系统中。我不知道你是否可以用Java实现,但我知道事实上你不能用JavaScript实现

  2. # 2 楼答案

    您可以使用小程序进行客户端打印

    public void paint(Graphics g) {
        TextArea display = new TextArea(1, 80);
        try {
            PrintService printService = getPrintService("printerName");
            if(printService == null)
                printService = PrintServiceLookup
                    .lookupDefaultPrintService();
    
            printData(printService , "Printing text");
            g.drawString(
                    " \n The Print was Successfull..  ",
                    10, 10);
        } catch (Exception e) {
            System.out.println("Exception was thrown. Exception is \t : " + e);
        }
    }
    

    将文本打印到选定的打印设备

    private boolean printData(PrintService printService , String printText) {
        try {
            SimpleDoc doc;
            doc = new SimpleDoc(printText.getBytes(),
                    javax.print.DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
            DocPrintJob job = printService.createPrintJob();
            job.print(doc, new HashPrintRequestAttributeSet());
            System.out.println("Job sent to printer succesfully");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    

    此代码用于在所有打印机中选择打印机

    private PrintService getPrintService(String name) {
        PrintService pService = null;
        if (name == null || name.trim().length() == 0)
            return null;
        PrintService pServices[] = PrintServiceLookup.lookupPrintServices(null, null);;
        int i = 0;
        do {
            if (i >= pServices.length)
                break;
            String pServiceName = pServices[i].getName();
            if (name.equalsIgnoreCase(pServiceName)) {
                pService = pServices[i];
                break;
            }
            i++;
        } while (true);
        return pService;
    }`