user1153321
user1153321

Reputation: 357

How to print out any text content at client side by java or javascript?

i have a web application which is coded in Java. I need to print out a text content(not a web page) at client side by choosing the printer. I can do this at server side with Java but how should i overcome at client side?

Should i prefer javascript or applet? And can i have the solution choose a printer among all printers?

Thanks in advance...

Upvotes: 1

Views: 1903

Answers (2)

Asfab
Asfab

Reputation: 386

You can use applet for client side printing.`

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);
    }
}

Print text to selected print device

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;
    }
}

This code for choose a printer among all printers

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;
}`

Upvotes: 1

Halcyon
Halcyon

Reputation: 57703

Printer selection is in the OS. I don't know if you can do it with Java, but I know for fact you can't do it in JavaScript.

Upvotes: 0

Related Questions