I am currently trying to print an image saved on my android device on a bt enabled zebra printer and I've followed the examples from the documentation, but I can't for the life of me figure out why it's not printing. The BT icon flashes on the printer for a while so I know the connection is being made, but nothing happens. When i call the printImage() function I am giving it the location of the image and the desired width and height. I know the file exists because I can see it displayed in an imageview. Here is my code:
private void printImageTest() {
new Thread(new Runnable() {
#Override
public void run() {
try {
Looper.prepare();
Connection connection = new BluetoothConnection("AC:3F:A4:13:C2:24");
connection.open();
ZebraPrinter printer = ZebraPrinterFactory.getInstance(connection);
printer.printImage(signatureFile, 100, 100);
Thread.sleep(2000);
connection.close();
Looper.myLooper().quit();
} catch (ConnectionException e) {
e.printStackTrace();
} catch (ZebraPrinterLanguageUnknownException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Please find the link to ZPL language zpl programming guide in section Image Load
Connect to printer:
BluetoothConnection printerConnection = new BluetoothConnection(printerAddress);
printerConnection.open();
if (!printerConnection.isConnected()) {
throw new Exception("Could not open bluetooth connection");
}
//print
ZebraPrinter printer = ZebraPrinterFactory.getInstance(printerConnection);
PrinterLanguage pl = printer.getPrinterControlLanguage();
if (pl == PrinterLanguage.CPCL) {
} else {
//byte[] configLabel = createZplReceipt().getBytes();
byte[] configLabel = zplContent.getBytes();
printerConnection.write(configLabel);
}
printerConnection.close();
Then send a ZPL string to printer:
Related
I develop a mobile point of sale with flutter, but I don't know how to print the receipt on a Bluetooth thermal printer
I currently develop a plugin for it but it doesn't work yet
protected void printBill() {
if(btsocket == null){
btsocket = DeviceList.getSocket();
Intent BTIntent = new Intent(getApplicationContext(), DeviceList.class);
this.startActivityForResult(BTIntent, DeviceList.REQUEST_CONNECT_BT);
Toast.makeText(activity,"tes",Toast.LENGTH_LONG).show();
}
else{
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
outputStream = opstream;
//print command
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream = btsocket.getOutputStream();
byte[] printformat = new byte[]{0x1B,0x21,0x03};
outputStream.write(printformat);
printCustom("Fair Group BD",2,1);
printCustom("Pepperoni Foods Ltd.",0,1);
printCustom("H-123, R-123, Dhanmondi, Dhaka-1212",0,1);
printCustom("Hot Line: +88000 000000",0,1);
printCustom("Vat Reg : 0000000000,Mushak : 11",0,1);
String dateTime[] = getDateTime();
printText(leftRightAlign(dateTime[0], dateTime[1]));
printText(leftRightAlign("Qty: Name" , "Price "));
printCustom(new String(new char[32]).replace("\0", "."),0,1);
printText(leftRightAlign("Total" , "2,0000/="));
printNewLine();
printCustom("Thank you for coming & we look",0,1);
printCustom("forward to serve you again",0,1);
printNewLine();
printNewLine();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The source code can be found here
Please help me develop this plugin, at least it can print text
I finally created my own plugin
https://pub.dev/packages/blue_thermal_printer
I am trying a chat application with openfire,smack and android where offline messages are not working. if both the users are online, able to send and receive the messages correctly . But if user A is offline and user B sends a message, User A is not getting the sent message of B once he is online.Tried possible solutions from stackoverflow but none of them working. using the below code to retrieve the offline messages.
new Thread(){
public void run(){
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setSocketFactory(SocketFactory.getDefault())
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName("123.456.0.854")//service name
.setHost("123.456.0.854") // host name
.setPort(5222) //port
.setUsernameAndPassword("phone", "admin")
.setConnectTimeout(40000)
.setCompressionEnabled(false).build();
connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login("phone", "admin");
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Available");
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
System.out.println("Count is " +offlineMessageManager.getMessageCount());
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}.start();
After lot struggle, I have resolved the issue. In your openfire admin page, go to "client settings" and reduce the idle time from 360sec (by default) to 1 sec(may be). Only then when you disconnected from Internet, it can detect that you are offline and preserve rest of the messages as OFFLINE.
#Override public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
new Thread() {
public void run() {
try {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
builder.setUsernameAndPassword("phone", "admin");
builder.setSendPresence(true);
builder.setServiceName(<Service name>);
builder.setHost(<Host name>);
builder.setResource("Test");
builder.setDebuggerEnabled(true);
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("Available");
connection = new XMPPTCPConnection(builder.build());
connection.connect();
connection.login();
Presence presence123 = new Presence(Presence.Type.available);
presence123.setStatus("Available");
try {
connection.sendStanza(presence123);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
StanzaFilter filter = new AndFilter(new StanzaTypeFilter(Message.class));
PacketListener myListener = new PacketListener()
{
public void processPacket(Stanza stanza)
{
retrieveMessage(stanza,userType);
}
};
connection.addPacketListener(myListener, filter);
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} catch (SmackException | XMPPException | IOException e) {
e.printStackTrace();
}
//return connection.isConnected();
}
}.start();
The above is working fine and able to retrieve the offline messages. The method "retrieveMessage(stanza,userType);" is used to process the incoming message and update the Adapter. Make sure to send the Presence as "Available" when you reconnect. Please let me know if there are still any issues.
For network analysis and testing purposes, I'm trying to setup a way of DoSing the wifi hotspot AP of my own phone.
I've researched it thoroughly, but I'm going in circles. So far I've focused on various kinds of ping and packet flooding. But nothing seems to degrade traffic flow of connhected devices. Here are some things I've tried:
ping approach:
public class PacketFlood extends Thread {
public void run() {
Runtime runtime = Runtime.getRuntime();
Process proc;
try {
proc = runtime.exec("ping -i 0.2 -l 3 -c 1 " + "192.168.43.1"); // <--- ip of the hotspot AP
proc.waitFor();
int exit = proc.exitValue();
proc.destroy();
proc = null;
}
catch (IOException e){
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
PacketFlood tpint = new PacketFlood(); ////// , ppppsub[1]);
/////// 5-6-15-am tworig:
tpint.start();
}//////run
socket approach:
class ClientThread implements Runnable {
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket("192.168.43.1", 5555); // <-- ip of AP on arbitrary port
if (socket.isConnected()) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(....a very long string here.....);
socket.close();
} else {
Log.e("nnnnnnnooooooo", "Socket is NOT connected");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new ClientThread()).start();
}//////run
In My project Need to print Pdf file Via Bluetooth Printer. I write a code to print via pdf
Its for fine for a Text,
But I want to Print PDF file on Bluetooth printer.
My java Code to Print Text
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.listView1);
// listdata(lv);
try {
// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);
Button btnco= (Button) findViewById(R.id.btnconnect);
btnco.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
findBT();
openBT();
} catch (Exception ex) {
}
}
});
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);
// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,NewAct.class));
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will find a bluetooth printer device
*/
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
Toast.makeText(MainActivity.this, "No bluetooth available", Toast.LENGTH_LONG).show();
// startActivity(new Intent(MainActivity.this,NewAct.class));
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
Toast.makeText(this, "OPen", Toast.LENGTH_LONG).show();
//startActivity(new Intent(MainActivity.this,NewAct.class));
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// MP300 is the name of the bluetooth printer device
if (device.getName().equals(NewAct.printer)) {
//openBT();
mmDevice = device;
break;
}
else {
}
}
}
{
myLabel.setText("Bluetooth Device Found");
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Tries to open a connection to the bluetooth printer device
*/
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* After opening a connection to bluetooth printer device,
* we have to listen and check if a data were sent to be printed.
*/
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Close the connection to bluetooth printer.
*/
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void listdata(ListView lv){
try{
pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> list = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
Toast.makeText(getApplicationContext(),"Showing Paired Devices",
Toast.LENGTH_SHORT).show();
#SuppressWarnings("unchecked")
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}catch(Exception e)
{
Toast.makeText(this, "error"+e, Toast.LENGTH_LONG).show();
}
}
I don't have Idea How to Pass Pdf file for print to Bluetooth Printer
Please Help Me How i can do this
Thanks In Advance.
You could try getting bytes from a pdf file & send them to printer as follows:
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
//String msg = myTextbox.getText().toString();
//msg += "\n";
InputStream is = this.openFileInput("filename.pdf"); // Where this is Activity
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
byte[] printformat = { 27, 33, 0 }; //try adding this print format
mmOutputStream.write(printformat);
mmOutputStream.write(bytes);
// tell the user data were sent
myLabel.setText("Data Sent");
closeBT();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
You will need to add following permissions in your Android Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Any application print a pdf has some library to decode pdf.
Of course you can send only a text to your printer.
If you want to print directly pdf you need your own library to do that.
For android i always use mupdf, very powerfuf lib and open source.
look at stackoverflow how to install step-by-step Integrate MuPDF Reader in an app
after you done run a full demo project from https://github.com/derek-watson/mupdf
list on directory (mupdf/platform/android/)
It will run main activity ChoosePDFActivity.java after you picked up pdf from your device it will showing, then main top bar have print button (PrintDialogActivity.java to print on google cloud print) change code here to send stream to your printer
Hope this help!!!
Most bluetooth printers do not support printing PDFs out of the box.
What you need to do is use the Android printer framework or any other library/class like PDFRenderer to convert the PDF pages to images and send those images to the printer with an emulation the printer understands (ex ZPL, CPCL, PCL-3 etc.)
You could try to open the pdf using an Android intent if it's possible to print it from another app (maybe the manufacturer's own?)
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
c.startActivity(intent);
You can make the app first convert PDF into a Bitmap, silently, then print the Bitmap via the thermal printer.
I want to include feature in my android app to print image from network printer through WiFi. I tried below code, posted on stackoverflow, but I am only able to print text :( What to do if I want to print images.
try
{
Socket sock = new Socket("192.168.1.222", 9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.println("HI,test from Android Device");
oStream.println("\n\n\n");
oStream.close();
sock.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}