Android print text on printer

2019-05-11 22:36发布

I am developing a restaurant app which print receipts after customer purchases foods. I have added a config screen in app which the manager uses to configure printers. A manager can print a test page to test whether he has entered right ip and port. Here is my code which prints test page:

private class PrintTask extends AsyncTask<Printer, Boolean, String> {

    @Override
    protected String doInBackground(Printer... params) {

        try {
            publishProgress(true);
            Socket sock = new Socket(params[0].getIp(), Integer.parseInt(params[0].getPort()));

            PrintWriter oStream = new PrintWriter(sock.getOutputStream());
            oStream.printf("--------------------------------\r\n");
            oStream.printf("***        TEST PRINT       ***\r\n");
            oStream.printf("You have configured your \n\r");
            oStream.printf(params[0].getName());
            oStream.printf("\r\nprinter successfully\n\r");
            oStream.printf("|           Thanks             |\r\n");
            oStream.printf("--------------------------------\r\n");
            oStream.close();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        publishProgress(false);
        return "";
    }

    @Override
    protected void onProgressUpdate(Boolean... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        if(!values[0]) {
            waitView.setVisibility(View.GONE);
        }
        else {
            waitView.setVisibility(View.VISIBLE);
        }
    }

}

The problem is if I print on a network printer (a stand alone printer without attaching to any PC) it prints text properly. Here I am using the ip and default port 9100. But when I print to a shared printer attached to a PC, it fails to print. Any idea, where I am doing wrong...???

1条回答
一夜七次
2楼-- · 2019-05-11 23:04

From what your describe it looks like that standalone printer is running some kind of "text printing service" on your given port. So looks like everything you send to this port will be printed as text.

Whereas when you have "Shared" printer on your Windows machine, it's implemented using Windows Printer service or smth like that. It's not just simple socket/port anymore where you can write ASCII text.

查看更多
登录 后发表回答