Android — печать из приложения на мобильном принтере

#android #cordova #mobile #printing #bluetooth

#Android #кордова #Мобильный #печать #bluetooth

Вопрос:

У меня есть приложение, которое печатает некоторый текст с помощью мобильного принтера Rongta RRP-200, подключенного к моему телефону через blueetoth.

Для этого я использую этот плагин: https://github.com/srehanuddin/Cordova-Plugin-Bluetooth-Printer

Я могу подключить свое устройство к принтеру и даже запустить функцию печати из своего приложения, которая возвращает мне сообщение, информирующее меня о том, что данные были отправлены. Однако принтер ничего не делает (за исключением включения его индикаторов).

Это функция (из плагина), которая пытается распечатать мой текст:

 boolean printText(CallbackContext callbackContext, String msg) throws IOException {
    try {
        mmOutputStream.write(msg.getBytes());

        // tell the user data were sent
        //Log.d(LOG_TAG, "Data Sent");
        callbackContext.success("Data Sent");
        return true;

    } catch (Exception e) {
        String errMsg = e.getMessage();
        Log.e(LOG_TAG, errMsg);
        e.printStackTrace();
        callbackContext.error(errMsg);
    }
    return false;
}
 

Что здесь может пойти не так?

Ответ №1:

Обнаружено, что плагин работает корректно, но вы должны предоставить принтеру полную строку, чтобы он что-то напечатал. Поэтому добавьте n в конце строки. Это функция для печати чего-либо, на случай, если кому-то это понадобится (в контроллере Ionic app):

 $scope.print = function(text) {
    BTPrinter.connect(function(data){
        BTPrinter.printText(function(data){
            BTPrinter.disconnect(function(){},function(err){
                console.log("Error");
                console.log(err)
            }, "Your Printer device")
        }, function(err){
            console.log("Error");
            console.log(err)
        }, text   "n")
    }, function(err){
            console.log("Error");
            console.log(err)
    }, "Your Printer device");
}
 

Ответ №2:

Ну, у меня такой же принтер, и я написал небольшой плагин, его работа для меня потрясающая. Я тестировал в RPP200 и RPP300.

https://github.com/CXRom/cordova-plugin-rpp

 Rpp.Connect("00:0E:0E:0B:7B:93", // <-- MAC Address of the printer
  function(print) {
    //At this point we send the action but we need to wait until the connection
    console.log(`connect ok ${JSON.stringify(print)}`);
  },
  function (err){
    console.log(`connect err ${JSON.stringify(err)}`);
  });

//Ask is device is connected
Rpp.IsConnected(function(conn) {
  //Send to print
  Rpp.Print({
    marginTop: 10, //Margin before print
    marginBottom: 10, //Margin after print
    lineSpacing: 50, //Size of line
    lines: [ //Lines to print
      { text: "Title", align: 1, bold: true, underline: true, size: 17 }, //long name properties
      { text: "Subtitle", a: 1, b: true, u: true, s: 17 }, //short name properties
      { text: "normal line" },
      { text: ":)", h: true }
    ]
  }, function(res) {
    console.log(`print ok ${JSON.stringify(res)}`);
  }, function(err){
    console.log(`print err ${JSON.stringify(err)}`);
  });
}, function(err) {

});
 

Комментарии:

1. Работает ли это с указанием имени принтера?