1

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

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

提前致谢...

4

2 回答 2

1

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

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;
}`
于 2013-11-26T06:24:46.717 回答
0

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

于 2013-10-03T15:12:24.280 回答