Printing a printer form using Socket Connection in Android

I have made a socket connection with a printer, but I cannot print. Creating a Connection class makes a socket connection to a printer and prints using the writeFromInputToOutput method. I read the file and write to the printer socket but nothing prints to the printer.

Below is my code:

    class MakeConnection extends AsyncTask<String, Void, String>{
        Socket sock = null;
        OutputStream oStream = null;
        File file;
        @Override
        protected String doInBackground(String... params) {
            try {
                sock = new Socket(ipAddress, 9100);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                // Do something
                // lollipop and above versions
                folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),folderName);
                if(!checkPermissions()){
                    requestPermission();
                }
                 file = new File(folder + "/" + filename /*"/Mypdf/Read.pdf"*/);
            }
            InputStream is = new FileInputStream(file);
                oStream = sock.getOutputStream();
              writeFromInputToOutput(sock,  is, new DataOutputStream(oStream));
            } catch (IOException e) {
                e.printStackTrace();
                Logger.LogError(TAG, e.toString());
                AppToast.showShortToast(mContext, e.toString());
            }
            return "";
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }


    public  void writeFromInputToOutput(Socket socket,InputStream is,  OutputStream os) throws IOException {
        byte[] buffer = new byte[10000];
  try {
            int count = is.read(buffer);
            while (count != -1) {
                String strindRead = Base64.encodeToString(buffer, 0);
                os.write(buffer, 0, count);
                os.write("\r\n".getBytes());
                os.write("PRINT\r\n".getBytes());
                os.write("PRINT\r\n\f".getBytes());
                os.flush();
                Logger.LogError("STRINGREAD", strindRead);
                count = is.read(buffer);
            }
        }
        finally {
            is.close();
            os.close();
            socket.close();
        }
    }

      

+3


source to share





All Articles