Recently, I was asked to make a program for printing some data to a small or handheld Bluetooth printer device.
This can be used for printing receipts, simple tickets, or customer notes.
I like how it works because usually, we are getting our program output on a computer screen.
But this time we are getting our output on a tangible paper!
This code will simply let you connect to the Bluetooth printer, type a text that you want to be printed and click the “send” button to print.
As for the printing with images, we made another code for that, please see section 4.3 (April 15, 2015 update) below!
1.0 Bluetooth Printing Source Codes
Step 1: Put the following code on your MainActivity.java. These imports are needed to perform our Android printing operations via Bluetooth.
import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.TextView; import android.widget.EditText; import android.widget.Button; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.UUID; public class MainActivity extends Activity { }
Step 2: Inside your MainActivity class will be the following variable declarations.
// will show the statuses like bluetooth open, close or data sent TextView myLabel; // will enable user to enter any text to be printed EditText myTextbox; // android built in classes for bluetooth operations BluetoothAdapter mBluetoothAdapter; BluetoothSocket mmSocket; BluetoothDevice mmDevice; // needed for communication to bluetooth device / network OutputStream mmOutputStream; InputStream mmInputStream; Thread workerThread; byte[] readBuffer; int readBufferPosition; volatile boolean stopWorker;
Step 3: After the variable codes, we will have the following onCreate() method.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // more codes will be here }catch(Exception e) { e.printStackTrace(); } }
Step 4: Our XML layout file called activity_main.xml located in res/layout/ directory will have the following codes.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="10dp"> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:" /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/label" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/entry"> <Button android:id="@+id/open" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:text="Open" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" /> <Button android:id="@+id/close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" /> </LinearLayout> </RelativeLayout>
Step 5: Inside the try-catch of your onCreate() method we will define the TextView label, EditText input box and buttons based on our XML layout file in Step 4.
// we are going 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); // text label and input box myLabel = (TextView) findViewById(R.id.label); myTextbox = (EditText) findViewById(R.id.entry);
Step 6: We will set the onClickListener of our open button. This will open the connection between the android device and Bluetooth printer.
// open bluetooth connection openButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { findBT(); openBT(); } catch (IOException ex) { ex.printStackTrace(); } } });
Step 7: findBT() method will try to find available Bluetooth printer. It will not work without the following code. Put it below the onCreate() method.
// this will find a bluetooth printer device void findBT() { try { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null) { myLabel.setText("No bluetooth adapter available"); } if(!mBluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { // RPP300 is the name of the bluetooth printer device // we got this name from the list of paired devices if (device.getName().equals("RPP300")) { mmDevice = device; break; } } } myLabel.setText("Bluetooth device found."); }catch(Exception e){ e.printStackTrace(); } }
Step 8: openBT() method will open the connection to Bluetooth printer found during the findBT() method. It will not work without the following code. Put it below the findBT() method.
// 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 (Exception e) { e.printStackTrace(); } }
Step 9: We need beginListenForData() method so that openBT() method will work.
/* * 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 ); // specify US-ASCII encoding final String data = new String(encodedBytes, "US-ASCII"); readBufferPosition = 0; // tell the user data were sent to bluetooth printer device handler.post(new Runnable() { public void run() { myLabel.setText(data); } }); } else { readBuffer[readBufferPosition++] = b; } } } } catch (IOException ex) { stopWorker = true; } } } }); workerThread.start(); } catch (Exception e) { e.printStackTrace(); } }
Step 10: We will make an onClickListener for the “Send” button. Put the following code after the onClickListener of the “Open” button, inside onCreate() method.
// send data typed by the user to be printed sendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { sendData(); } catch (IOException ex) { ex.printStackTrace(); } } });
Step 11: sendData() method is needed so that the “Open” button will work. Put it below the beginListenForData() method code block.
// this will send text 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 (Exception e) { e.printStackTrace(); } }
Step 12: We will code an onClickListener for the “close” button so we can close the connection to Bluetooth printer and save battery. Put the following code after the onClickListener of the “Send” button, inside onCreate() method.
// close bluetooth connection closeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { closeBT(); } catch (IOException ex) { ex.printStackTrace(); } } });
Step 13: closeBT() method in Step 12 will not work without the following code. Put it below the sendData() method code block.
// close the connection to bluetooth printer. void closeBT() throws IOException { try { stopWorker = true; mmOutputStream.close(); mmInputStream.close(); mmSocket.close(); myLabel.setText("Bluetooth Closed"); } catch (Exception e) { e.printStackTrace(); } }
Step 14: Make sure the BLUETOOTH permission was added to your manifest file. It is located in manifests/AndroidManifest.xml, the code inside should look like the following.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.bluetoothprinter" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <supports-screens android:anyDensity="true" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
2.0 LEVEL 1 Source Code Output
Step 1: Click the “Open” button, the “Type here” text will change to “Bluetooth Opened”
Step 2: Type any text in the text box or EditText.
Step 3: Click the “Send” button, Bluetooth Printer device will print the text you typed in Step 2.
Step 4: Click the “Close” button to close Bluetooth connection and save battery.
Need to buy the same printer model we used above? I will give you the contact information of our supplier. Send an email to mike@codeofaninja.com with a subject “Bluetooth printer by codeofaninja.com”. I will reply with the contact information of our supplier.
3.0 LEVEL 2 Source Code Output
The LEVEL 2 source code can print small images. As you will see in the video, you can browse the image and then the Bluetooth printer will print it.
Need to buy the same printer model we used above? I will give you the contact information of our supplier. Send an email to mike@codeofaninja.com with a subject “Bluetooth printer by codeofaninja.com”. I will reply with the contact information of our supplier.
Please note that you have to pair your Android device (in your Bluetooth settings) and Bluetooth printer before running our source code.
4.0 Download Source Code
4.1 Downloading The Source Code
You can get the source code by following the source code above. But isn’t it more convenient if you can just download the complete source code we used, import it and play around it?
There’s a small fee in getting the complete source code, it is small compared to the value, skill upgrade, and career upgrade it can bring you, or income you can get from your android app project or business.
Download the source code by clicking the “Buy Now” button below. What will you get? The source codes and free code updates!
4.2 LEVEL 1 Source Code
LEVEL 1 is the complete source code of our tutorial above.
4.3 LEVEL 2 Source Code
Here’s the source code version where you can print images (see output video demo on section 3.0 above). The source code can let you browse an image and then print it in the Bluetooth printer.
Images must be small and less than 10KB in size only, anything more than that, the printing will fail.
4.4 Download ALL LEVELS Source Code
This means you will download LEVEL 1 and LEVEL 2 source codes above at a discounted price.
IMPORTANT NOTE: This code was only tested with the printer we specified above. It may not work with your kind of printer. We provide the code as is. Download it at your own risk.
Also, thanks to a code from project green giant for helping me figure out this Android Bluetooth printing code example.
288 responses to “Android Bluetooth Printing Example Code with Actual Printer Device”
could you please explain use of beginListenForData()
Hi @384f8d64c77e5048c202661b78d018ae:disqus , I think that’s just a worker thread waiting to be interrupted by the user (when he click the send button). It analyzes the structure of the data to be printed by bytes and check for delimeter, etc… Anyone out there got better explanation? :)
Hi! I have a question. Is possible to adapt this code to an application based in c#? because I have problems doing this. I am using Xamarin Studio. Thanks …
Hi! I use Xamarin too. Do you find the solution ?
Hi Jr Good, I have also the same problem, did you find the solution?
Bluetooth program i try to add multiple text field that time i try to open Bluetooth but it is not open why?
Hi @shibu babu, why would you want to add another edit text? you can also just concatenate the values of those edit text to be printed…
BUFFER ISSUE ??
I use several mmOutputStream.write in my app,
i.e. one by ‘printer command’, line to print, … but I have problem that not always all my requests seem to be sent to the printer. Can it be I must do all in one write only ??
thanks you very much boss u cleared me all concept about …
Hi @SAN, I’m glad it helped. :)
Hi am getting connection refused exception any IDEA
Here am getting Null Pointer Exception
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
Hi @e05d760241935e822cad6d2c163e0029:disqus, did you make sure your bluetooth device is connected? See this part of the code…
if (device.getName().equals(“MP300”)) {…
MP300 might not be the name of your bluetooth device…
Hi Mr. Mike, So How can i get the name of my device ? and if he is necessary ?
Hi @Marwen, you can get the name of the device when you open it and your phone scans the available bluetooth device. You might find it in the packaging of your bluetooth printer device.
is it possible to print a JPEG file?
Hi @disqus_gKsORpBJYl:disqus, sorry I haven’t tried that yet…
Is anyone else getting an error in the MainActivity.java file?
I am using eclipse and simply just imported this file into my IDE. I would love to play around with this application
yo
pudiste encontrar solucion?
I am Trying to print a Receipt after every transaction (payment in my case). But i am facing a problem when i give print one after the other i.e.; when i give a print for more than two times my App is getting Struck
hi
I m Trying to build Chat app. in my website with Login only unique id ans also store every chat history in my database;i can’t understand how to do please give me some guideline.
sumit kumar(sumitkasaudhan1@gmail.com)
can it print image sir?
Hi @disqus_zp86iO62M8:disqus , I haven’t tried it, sorry!
Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible
Hi @disqus_4YWarVSi2i:disqus, you can do it by posting the file to a server (first device), saving it there and then make the second device download it.
Sir you are saying right but i want to simply send data from one device to another .sir kindly give me the code and thanks in advance
sir i am waiting for your reply
Hi @disqus_4YWarVSi2i:disqus, sorry but this post does not cover your request, but a code here might help you http://stackoverflow.com/a/6274660/827418
SIr i try this code before basically major problem in this code is “uuid” is not present .SIr tell me what changes is reqiured in your project ” Bluetooth send data to Bluetooth printer “. My goal is to send file from one andriod phone toanother andriod phone through bluetooth .I know you will solve my problem as soon as possible sir i am waiting for your reply .
ahmed sir if you get this code than pls send me on my email id suryaprakashchamoli@gmail.com….thank you
sir i try this code before but this is not working .S ir what changes is required in your code ” Android Bluetooth Code to Print Text on a Bluetooth Printer “.
My goal is to send file from one andriod phone to another andriod phone .Sir i know you solve my problem plz sir reply me as soon as possible.thanks
Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible
Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible
Sir what change is required in your code “bluetooth send data to bluetooth printer” My goal is to send file from one andriod phone to another andriod phone and i know you solve my problem kindly answer me as soon as possible
Sir want change is reqiured in your code” bluetooth send data to bluetooth printer ” My goal is to send file from one andriod phone to another andriod phone i know you solve my problem as soon as possible.
Ahmed there is a example from google that is a chat that you can use.
In the specs says that yes
Hi!!! iIm having a problem in some device, it is working fine in Sony xperia and samsung galaxy, but not in Myphone and acer tablet. it doest’n connect to the printer..
Hi @igimaster:disqus, can you show us what the logcat says?
Hi! I have an Intermac printer, and it doesn’t accept pairing, is there a way to send the printer data, without pairing (bonding) the device, I’m trying to do it, but it promts me a message to enter the pin, and when I fail to do that it throws an exception
Hi @e256105adfdcaa924ee0bca596d75070:disqus, I think it really needs pairing since this is the industry standard for bluetooth.
Hi,
a very nice example of working
Russian characters unit does not print properly (Windows-1251 encoding of the printer)
What can we do about it?
Printer model=Sewoo lk-p30
Thanks
Hi @kadirleblebici:disqus, thanks for visiting, are you sure your printer is capable of printing russian characters?
You might also want to play with this line of code:
final String data = new String(encodedBytes, “US-ASCII”);
by changing US-ASCII to Russian encoding, this link might help you http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx
Awesome it works with any other printer too!!!
Hi @dibbstar, good to hear it works on your printer devices! Thanks for telling us. :)
AWESOME JOB!:. THank you so much.. it helped me a lot.. the only problem I had.. was that this permission was missing in the in the manifest, without it I counldn’t print.
But everything else works fine :D
Hi @SantiMe, glad it works for you! Thanks for letting us know!
Please mike I have tried to implement this code in oracle mobile application framework (android version) environment but it couldnt connect with rpp300 printer .I use oracle mad 2.3 to developed android applications.
http://www.oracle.com/technetwork/developer-tools/maf/overview/index.html
https://blogs.oracle.com/mobile/entry/maf_2_3_release
Any help or suggestion ??
i have same problem my send and close buttons not perform any action so please i was used same above code in my project but we face issues so any one face this type of issue
Brilliant! , It’s a lot better than Google’s example (BluetoothChat )!!!
HI @alexbrsp:disqus, thanks, good to hear you liked this example! :D
Hy! I have a problem, on this string mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
And not performed on. Pleas help!
How to print Tamil characters sir…
Wich printer do you use???? PLEASEE!!!
Hi @mauricabreraestrada:disqus, I think I was using MP300 portable printer.
Hi! i’m having a problem in some device, My’s device Samsung galaxy note 2 and printer epson lq300 [have bluetooth printer adapter act bt5800 ub]
please help
Hi @takizwanarin:disqus, what exactly is the problem you’re facing, can you tell us some error messages? We don’t have your devices to test it out. Thanks! :D
Hi Murugan, did you already try it using a different character encoding?
Yes sir..i think my (MPD2 bluetooth printer)printer does not support for tamilcharacters… which printer will support tamil font pls tell me sir…
I am using samsung galaxy pocket with Blue Bamboo printer but it does not send any command to the Printer it only write Bluetooth Device found. Please help me out .
Hi @Osman, does your samsung galaxy pocket detects your printer device?
ok, works great, but i want print a pdf file, what can i do?
have you figured it out? I am in need of similar..
I also require the same(printing a file).
Please let me know if any have got any answer.
Sorry for the late reply @juanjosemirc:disqus, I think what you need now is a large printer device and not like the example above where you print on a small and handheld printer device. I have no experience printing a pdf file in this case.
OK, i see, but forget the pdf file. How can i print a picture, a litte picture like a logo. is it possible? your android code is very good for text, but i want print a picture or a file, please help me, thanks!
@juanjosemirc:disqus and others who require printing an image or pdf files, I added an important note above stating that the code can print only texts. Some good people might want to contribute to this post and add that functionality.
Right now, I don’t have enough time to research about it, but if I have, I’ll surely update this post and notify you via email (if you’re subscribed), thanks for understanding!
Ok, thanks a lot! I want print a image, but i can wait and go on searching in the web
;)
Which printer do you use(printer company name and also model number)? Because I am new in android. please help me. Also this printer is available in India ?
I can not download your source code. please send me download file if it is possible.
please tell me which printer( company name & model no.) did you used in this program.
I am new in android, please help me.
Hi, I am trying to print an invoice using a bluetooth printer. There is no issue with the printing. The issue is the data formatting before printing. The data gets shattered in the receipt. I used Outputstream to print and passed string to that.Please do reply if there is any solution to format the data before printing.
Its depend on your printer, Sample shown below are apex3 printer code….
public class PrinterCommands {
public static byte[] INIT = {27, 64};
public static byte[] RESET = {24};
public static final byte[] AUTO_POWER_OFF = {27,77,55,54,53,52,48,13};
public static byte[] SELECT_FONT_A = {27, 33, 0};
public static byte[] SELECT_FONT_12 = {27, 75, 49, 13};
public static byte[] SELECT_FONT_25 = {27, 75, 49, 49, 13};
public static byte[] FONT_BOLD_ON = {27, 85, 49};
public static byte[] FONT_BOLD_OFF = {27, 85, 48};
public static byte[] FONT_UNDERLINE_ON = {27, 85, 85};
public static byte[] FONT_UNDERLINE_OFF = {27, 85, 117};
public static byte[] FONT_HI_ON = {28};
public static byte[] FONT_HI_OFF = {29};
public static byte[] FONT_WIDE_ON = {14};
public static byte[] FONT_WIDE_OFF = {15};
public static byte[] CHAR_SET = {27, 70, 49};
public static byte[] PRINT_LEFT = {27, 70, 76};
public static byte[] PRINT_RIGHT = {27, 70, 86};
public static byte[] SET_BAR_CODE_HEIGHT = {29, 104, 100};
public static byte[] PRINT_BAR_CODE_1 = {29, 107, 2};
public static byte[] SEND_NULL_BYTE = {0x00};
public static byte[] SELECT_PRINT_SHEET = {0x1B, 0x63, 0x30, 0x02};
public static byte[] FEED_PAPER_AND_CUT = {0x1D, 0x56, 66, 0x00};
public static byte[] SELECT_CYRILLIC_CHARACTER_CODE_TABLE = {0x1B, 0x74, 0x11};
}
and sample below how to use it
mmOutputStream.write(PrinterCommands.INIT);
mmOutputStream.write(PrinterCommands.SELECT_FONT_25);
mmOutputStream.write(PrinterCommands.FONT_HI_ON);
mmOutputStream.write(PrinterCommands.RESET);
thanks, I need this codes for Zebra MZ320 printer, where can I find it ?
Its depend on your printer, Sample shown below are apex3 printer code….
and sample below how to use it
mmOutputStream.write(PrinterCommands.INIT);
mmOutputStream.write(PrinterCommands.SELECT_FONT_25);
mmOutputStream.write(PrinterCommands.FONT_HI_ON);
mmOutputStream.write(PrinterCommands.RESET);
Hello, can you help me?
I need to print to the printer ─ characters chr (196) chr ┼ (197) ├ chr (195), ┬ chr (194), etc..
I can not print these characters.
Sorry man I can seen to find a solution too… why do you want those characters anyway?
What model of printer and android device do you have?
Hi @igimaster:disqus, I was using model MP300 portable printer.
Thanks! and what brand and model your android device.
Do you know what is the apex 3 bluetooth pin?
Great tutorial. it’s a great help.
my problem is with the statement
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); -MainActivity.java:156)
mmSocket.connect();
my log:-
07-18 16:48:23.639: W/System.err(12643): java.lang.NullPointerException
07-18 16:48:23.669: W/System.err(12643): at com.example.bluetoothprinter.MainActivity.openBT(MainActivity.java:156)
07-18 16:48:23.669: W/System.err(12643): at com.example.bluetoothprinter.MainActivity$1.onClick(MainActivity.java:64)
07-18 16:48:23.669: W/System.err(12643): at android.view.View.performClick(View.java:3660)
07-18 16:48:23.669: W/System.err(12643): at android.view.View$PerformClick.run(View.java:14427)
07-18 16:48:23.669: W/System.err(12643): at android.os.Handler.handleCallback(Handler.java:605)
07-18 16:48:23.669: W/System.err(12643): at android.os.Handler.dispatchMessage(Handler.java:92)
07-18 16:48:23.669: W/System.err(12643): at android.os.Looper.loop(Looper.java:137)
07-18 16:48:23.669: W/System.err(12643): at android.app.ActivityThread.main(ActivityThread.java:4517)
07-18 16:48:23.669: W/System.err(12643): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 16:48:23.669: W/System.err(12643): at java.lang.reflect.Method.invoke(Method.java:511)
07-18 16:48:23.669: W/System.err(12643): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:995)
07-18 16:48:23.669: W/System.err(12643): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
07-18 16:48:23.669: W/System.err(12643): at dalvik.system.NativeStart.main(Native Method)
Hey @disqus_nYnzGXSTKm:disqus , thanks for the report, but does your app crashes? Or it just show these logs? If it works correctly, you can just catch these logs.
java.lang.NullPointerException
Suggests that you haven’t setup the uuid. So there isn’t a socket connected and it returns null.
How to format the string?
-> Header a bit bigger, bold and center aligned
-> setting text right/ left aligned
Hey @disqus_BtZeNQi3El:disqus , sorry I haven’t tried that one yet. Please let us know if you did it!
hi i did the code for print image get my email Wesleymontaigne@hotmail.com but pdf i can’t to do this
Hi @Wesley, you can print small image as seen in the video demonstration above. We haven’t tested this to print PDF content.
Hi, any luck with making print images? Tried everything i could but not working.
Hi,
The coding works perfectly, but i want to print all items from listview if number of columns and rows are available.
So please tell me how to print this. if you have any sample like this please give me
This is great tutorial, thanks .
Does any one know how i can format the print output to Bold, Italic and underline.
Hello @moiky:disqus, you’re welcome! However, I don’t know how to do that too, I haven’t tried it yet. Please let us know here if you were able to do that, thanks!
Right now all i can print is plain text with no format. I need to be able to format printed text to BOLD, Italic and underline
Do you knew how ?
Good job! Where do i order this kind of printer?
@Rolex, I think you can find it in amazon, alibaba or ebay..
Where can i buy/order MP300 mobile printer?plz help…
Hey Xzone, I’m sure you can find it in alibaba or amazon..
Can I order/buy this mobile printer in the Philippines..Sorry of my arrogant..heheh I’m new with this…
Hi Xzone, u got printer?
Guys, here’s the amazon link where you can buy the mobile printer http://www.amazon.com/gp/product/B01AG2C0G8/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01AG2C0G8&linkCode=as2&tag=codeofaninja-20&linkId=Z2FOSJPNSUWTGB6T
Great work, I am using your code to send data from my phone to PC. But it does not work. My PC use source code from https://www.dropbox.com/sh/31o42beyy1y3gv1/R4sPCdOs7G What is my problem?
Great work, I am using your code to send data from my phone to PC. But it does not work. My PC use source code from https://www.dropbox.com/sh/31o42beyy1y3gv1/R4sPCdOs7G What is my problem?
i have a question, to set the charset to latin charset ISO 8859-15, what is the decimal/hexadecimal comman???
thanks
Hello @disqus_jOagGBxHmJ:disqus, what part of the code will you use decimal/hexadecimal?
Maybe this post can help the people who want to print images throught the thermal printer.
http://stackoverflow.com/questions/14530058/how-can-i-print-an-image-on-a-bluetooth-printer-in-android
The key is set the correct values to the “public static byte[] SELECT_BIT_IMAGE_MODE” variable
For my image (380px width) the correct value was
public static byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33, 124, 1};
the first 3 parameters can be the same, the last 2 depends on the image width
380dec = 00000001 01111100
01111100 –> to dec = 124
00000001 –> to dec = 1
Hello @miquelmas:disqus, wow, thanks a lot for sharing this valuable info with us here, sure it will help a lot of people who wanna print images!
Thanks to you for your post! It was very usefull
Using Epson T70i(Thermal) printer, We can print images via Android Wifi Connection :D
Hey @disqus_gTHibeWSII:disqus, good to know you can do that with the help of our code, would you tell us specifically how you did print images? Thanks!
sir @ninjazhai:disqus epson already provided their android/ios sdk, also they include sample programs for that . :)
https://download.epson-biz.com/modules/pos/index.php?page=prod&pcat=52&pid=2774
Here , What is UUID .
And this UUID is our android Device Ya Bluetooth Printer ,
and how to get UUID .
Hai ninjazhai. Thanks for the bluetooth prinitng code. Can u explain me the concept ‘beginListenForData()’ function.. i.e how it checks whether data is sent for printing.
Is there any other example for printing via network printer
@miquelmas:disqus Is it possible to have the source code of the app ???? plissss thanks
Awesome Work …. Thank you so much :)
You’re welcome @Osama!
is this code working with “zebra P4T Mobile Label Thermal Transfer Printer” ?
Hello @disqus_o0249IY8l8:disqus, unfortunately, I’m unable to test it with other printers. I hope you try it and let us know. Thanks!
hello BluetoothPrintImage buy the code to print the image but leaving some characters and not print the image, I wonder if I can help with the solution
Hello @benignovera:disqus, what printer model are you using? What error message in the logcat do you see?
It is zebra 220, in the code that I have to change if I can help, I will read the manual of the printer and the resolution you have is 203 bpi, with width of 56mm and 914 mm long.
hi thanks for reply, it is a zebra rw 220 printer prints this way, I can change in the code, if I can help.
@benignovera:disqus, what size of image are you using? Images must be small and less than 10KB in size only, anything more than that, the printing will fail. We can continue this discussion using email, send me an email at ninjazhai30@gmail.com, thanks!
Hi Mike, PLEASE NOSE SI revise the problem that I mentioned AND SEND THAT YOU WANT PRINTER PRINT, IS URGENT PLEASE THANKS
This is an awesome tutorial and I really appreciate.
Now the code is working perfectly, but I can only print once. When I attempt to print the second time, I get the error message below:
“java.io.IOException: read failed, socket might closed or timeout, read ret: -1”.
Can someone help me out on fixing this one?
Thnaks.
Hello @webville:disqus, thanks for the kind words! About your issue, have you tried the ‘close’ button before trying to print another one?
I really appreciate you getting back to me on this.
I was attemptiong to print dynamically created data from sqlite database. By the time I sent in my feedback, the printer was only printing once however, after abit of tinkering, I moved the closeBT() method to be executed just after the first receipt has been printed, and it is now working.
Your tutorial has helped me learn alot.
Thanks a bunch.
I see, glad it works for you now… Thanks for the kind words, you’re welcome @webville:disqus!
i have getting the same issue, i closed but getting the same issue plz help me…….
Hello @disqus_IxHvjtuQDV:disqus would you show us your logcat message?
hii @ninjazhai:disqus thank you for reply, i am sending the logcat of my errors.
Please see my reply on your other comment, thanks..
hii @Mike Dalisay some times data not sending to printer, data will be sent some times first atempt and sometimes two three atempts, what was issue pls find …..
hii @ninjazhai:disqus these are the logcat of my errors and also my bluetooth printer has 4 times connecting perfectly but 5th time onwords its not connecting, its show some error.the error in logcat messages….
Are you sure you poperly close the mmOutputStream, see the closeBT() method…
yes i closed, and also i tried to connect other smaple apps but getting the same error…
Thanks for the great post Mike.
Have you tried to align the printed characters – left align, which is the default, right and center align. If yes, could you please share the code to do this. I am stuck!
Thank you
Hello @disqus_jINABdnw23:disqus, I haven’t tried it, buy I’ll share it once I did it. You’re welcome!
Hello Good Citizen, I was trying to print dynamically created data from sqlite database, but I don’t know how to change the code of Mike Dalisay to do it. Do you convert your data in a file or something like that. I would appreciate a lot your reply.
Thanks a lot.
Tony
No.
Actually, as per Mike’s code, there is a variable msg. I get the records from the SQLite database, and assign them to that variable msg. The contents of msg is what I print out, and it is working perfectly.
hi
i want your help
i buy new mobile thermal printer
how can change sdk printdemo
for printing arabic
and print images
hi mr mike
i buy mobile thermal printer
i having problem with printing arabic
and barcode and images
can you help me for change sdk
Hi, please I need your help. I have implemented your code but on click on the Send button, It does not do anything and no error is shown. I’m using DPP 250 bluetooth printer.
I haven’t tried it with that printer, but would you show us your logcat messages?
Hi Mike!! Congrats for your tutorial. I need your help if its possible. How can i adapt your code to print from a list view based in created data from sqlite database.
Thanks a lot.
Thanks @Tony! About your question, you can always arrange your data from sqlite and put it in the “msg” variable under sendData() function. It’s just like passing the data you want to be printed..
Hello @ahmedibrahimm:disqus, I we talked via email few days ago. It worked with english and chinese characters. You have to contact your printer manufacturer about its configuration for printing arabic characters.
how can i print image
?
@disqus_Wy7mfWMI3I:disqus our LEVEL 2 source code above can do it.
Hey ! This is great !
AWESOME JOB MAN !
i needed this for a project !
but i am facing a problem, i have another bluetooth printer and its not working with it ?
Can you help please !
Hello @megatfive:disqus, thanks for the kind words! About your convern, would you specify the error or logcat message that you see there?
Hi Mike,, I am using hp officejet 100 mobile printer, I am able to send the data but data is not printing in printer Only i can see empty
Hello @Maqsood, would you tell us what your logcat says?
Can u share Printer shopping cart link..Because i searched lot i am not getting .,pls..
Hello @ananddoodleblueandroidteam:disqus, we are working on an android shopping cart source code. But for now, you can get an idea on how it will be done with our web version here https://www.codeofaninja.com/2013/04/shopping-cart-in-php.html
Hi,Where i get MP300 Printer
Here’s the Amazon link where you can buy the mobile printer above http://www.amazon.com/gp/product/B01AG2C0G8/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01AG2C0G8&linkCode=as2&tag=codeofaninja-20&linkId=Z2FOSJPNSUWTGB6T
Thanks for this awesome project! It seems like i can’t print out the message to the printer. here is the log.
01-26 09:55:43.377 13074-13074/com.hatching.mposprintertwo W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.bluetooth.BluetoothSocket android.bluetooth.BluetoothDevice.createRfcommSocketToServiceRecord(java.util.UUID)’ on a null object reference
01-26 09:55:43.377 13074-13074/com.hatching.mposprintertwo W/System.err: at com.hatching.mposprintertwo.MainActivity.openBT(MainActivity.java:136)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at com.hatching.mposprintertwo.MainActivity$1.onClick(MainActivity.java:62)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.view.View.performClick(View.java:5204)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.view.View$PerformClick.run(View.java:21153)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.os.Looper.loop(Looper.java:148)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at java.lang.reflect.Method.invoke(Native Method)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-26 09:55:43.378 13074-13074/com.hatching.mposprintertwo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
what is the problem actually? thanks.
Hi, you should be publish the image with you test… publish your superman logo… please for test, because i buyed that code and it’s fail… or give me any specification of the image… png, bmp, gif… size of image, dimentions… thanks for your work!!
Hello @elvalelucho:disqus, you’re welcome! Please see the new LEVEL 2 demo above. The only requirement is your image must not be more than 10KB.
Hello @ahmedibrahimm:disqus please make sure you bought the Bluetooth printer above in this link http://www.amazon.com/gp/product/B01AG2C0G8/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01AG2C0G8&linkCode=as2&tag=codeofaninja-20&linkId=Z2FOSJPNSUWTGB6T
Great work!!!! i just stubble on this today!!! i was so awesome. it save a lot of my headache.
Thanks Man!!
Wow, thanks for the kind words @stephenakin:disqus! Glad to help you!
pls how can i print a page of displayed activity directly to the Bluetooth printer
Hello Akin, pls I have not been able to make this code work, can you help?
Can I use this code for Woosim WSP i350 printer? Thank you in advanced
Hello @Haikal, I can’t say for sure because I don’t have that kind of printer to test it with.
Hi!, I have a question….
is this the only version (LEVEL 2) of the downloadable file? I download it time ago and run all ok, (when the page shows a MP300 printer) I lost the file, and download it again, but it don’t run like the last time, is this a newer version? if Yes, could you send me the old version ?
thanks a lot,
enrique
Hello @disqus_n1f2NimhSp:disqus, source code is almost still the same, the only change is before, I developed it in Eclipse, now it is developed in Android studio. Which one do you use currently? I’ll try to find the old file, please send me an email at mike@codeofaninja.com so I can know your email address
I guess its because you didnot get the device.
So device object is null and so further dependencies.
else {
readBuffer[readBufferPosition++] = b;
}
what is the b,,im not understand ?
can help me?
printer not respond when im click send button
Hello @net_kom:disqus, would you tell us what your logcat says? What printer do you use?
my bluetooth printer Zjiang POS Thermal Printer 57.5mm – ZJ-5890K – Black
@net_kom:disqus I do not have that kind of printer so it is very hard to replicate the issue and say what was wrong.
logcat object null
Hi, i have a Zebra printer, ZQ500 Series. do you know if the code will work on it? Thanks!
Hello @disqus_KRrNtzO1Tm:disqus, unfortunately, I don’t have that kind of printer. The best way to know if it will work is to test the source code with your printer.
hi i have tried this i have a question is if i want to print on another blutooth device is this works????and what i have to do on this way for different printer?
Hello @amdad hossain, I really can’t answer that question. The best way to know the answer is to test the source code with your printer.
Thanks for the code. I am trying to implement it with a non-brand POS printer. It’s not connecting. The connect() function leads to Local/Android/sdk/sources/android-22/android/bluetooth/BluetoothSocket.java where I am getting an error “cannot resolve symbol ‘IBluetooth’ ” in the line #301
IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
Being a new programmer, I can’t find a solution. It’d be really nice if somebody helps me out.
Hello @kamullick, are you sure your Bluetooth printer name is IBluetooth?
i want the same application in android for wifi and bluetooth both…. pls help
Hello @heminshah:disqus, we only tried it with Bluetooth connection.
Hi Mike…. Great work!!!! How can I print HTML text to format the content/text? Please help me
Hello @charmidesai:disqus, thanks for the kind words! Unfortunately, we haven’t tried to print HTML data.
Thank you mike for replying me. Have you tried to set the alignment of text?
this is just….wow……..Thanks friend
You’re welcome @me@meshileyaisrael:disqus!
HI a have a problem with this code.
error: “Attempt to invoke virtual method ‘void java.io.OutputStream.write(byte[])’ on a null object reference”
in this line: mmOutputStream.write(line.getBytes());
work on android studio 2.1, android version 5.1.1, java jdk1.8.0_91
thanks for your help
Hi @disqus_O6v8KoBrRe:disqus, what printer model are you using?
When there is no paper inside printer but it is connected with device and If I give print command it is showing printing successful but actually it is not printing.
Hi @disqus_TaUs88ROtP:disqus, thanks for telling us about this instance, but did it print when you put a paper?
Hello, yeah. But, as the mobile is connected with printer it always shows print successful though it is not printing for unavailability of paper.
Does it print PDF?
Hello @deepakdonde:disqus, we only tested it in text and image.
Hi, does this code supports multiple phones sending print requests to the same printer simultaneously? It’s not clear for me whether the connection should be closed right after printing so other phones can send data do the same printer, or if I can keep like 5 phones connected at the same time.
Hello @manowars:disqus , multiple android device can send print requests to the same printer but should be done one at a time. I believe you can connect 5 phones to the same printer at a time but sending print requests at the same time could cause errors.
Thank you.
I was wondering if I can keep the phones connected to the printer or if I have to disconnect after printing each receipt.I thought that keeping the connection was preventing to print from more than one device at the same time.
Hi, This is great. But I am facing formatting issues, the content is printing continuously not line by line. I think msg += “n”; is not working, could you please suggest how to fix it.
I’m using a Zebra iMZ printer. This code does not seem to work for me but , I’ve found that you need to put “rn” at the end of every line, not just “n”
Thanks for sharing your solution @yaskinforrit:disqus! I’m sure this will be useful for Zebra iMZ printer users!
If you don’t mind, what error message do you encounter that our code above did not work for you?
HI,why this sample can’t show traditional Chineseword of use UTF-8 Type?
It can show Simplified Chinese word like this:
mmOutputStream.write(msg.getBytes(“GBK”));
Awesome, thanks for this tip @hadeser:disqus !
Thanks very much !
You’re welcome @hadeser:disqus !
hello, thank you for proving such a wonderful post, my question is, how would I go about incrementing the text size when print is executed?
Thank you
Hello Juan, I’ll try to find out if that’s possible. If it is, I’ll reply to you here. Thanks.
it connects to only one printer.how to connect each printer which is paired or available
plz reply me
Hello @dhanraj_hospet:disqus , I don’t think you can connect multiple devices to one printer at the same time.
Thanks for your nice tutorial. Is there any way to get notification from printer to mobile that my sending command is not printed properly ?
this is working for me
Hi Sir, I am developing app in Ionic 1, is there any code to print via bluetooth printer in ionic app?
Please help me sir,
Hi friend, do you have some example to Xamarin with VS? i can pay you but this
Ever find any Xamarin examples?
No :(
Hi, Are you waiting for any acknowledgment here form printer . if yes why it is required? I trying this by using ESC Sequence. but it picking up some random values.
Is this code work only for this printer or can work for all ?
We only tested it on the printer above.
Would you like to know if this code works on the Knup bluetooth printer (kp-1019)? I want to pay for the code, but I need to make sure it works on the printer I own! Grateful!
Unfortunately, we are unable to test it on that kind of printer because we don’t have one. We only tested the code on the printer above. Download at your own risk.
The code works perfectly and you save my life, Thanks
Paul, glad our source code and tutorial helped you! Thanks for letting us know that it worked for you. :)
Hello,
I need your code for android application so please me i am waiting for your response
Hi @faizal, you can always use the green download button above.
Hello i am interested to buy your code so please contact me
Hi @faizal, please send an email to mike@codeofaninja.com with your list of questions.
Hi Mike,
could post t your source code
Hi @jayapriya, code is already on the tutorial above.
please i want help . can i contact with you. i have rongta printer RP80 without bluetooth or wifi
Great tutorial, definately gonna try it..
I have a question, is it possible to print a PDF by this code?
Hi @Muhitun, thank for the kind words! We haven’t tested this to print PDF content. Would you explain your situation, why do you want to print PDF?
Hi.
Do you have a USB printing example source code for this printer?
Regards.
HI, where does the binding actually happen? In findBT() you do Set pairedDevices = mBluetoothAdapter.getBondedDevices(); but that won’t return anything if no devices actually bonded with the device, correct?
Dear Mr.Mike is the UUID is standard ? i mean in this code i have to only change the name of my Bluetooth device ?
Hi friend ,
Your code working perfect. Is there a way to align text to right left as a table.
Thanks. :D
Excelente!, gracias amigo funciona a la perfección solo cambiando el nombre del dispositivo Bluetooth Mil gracias
Hi ,
We are looking for driver for following device below and need to print PDF doc from tablet to printer.
Printer: Bluetooth Printer SEWOO LK-P30
Tablet: Samsung SM-T231, Galaxy Tab4 7.0 3G (Android OS, v4.4.2 (KitKat))
Thanks waiting for your reply
Hi. when i implement your code it seems that the send and close button is not working. whenever i click the sent button it has an error java.lang.NullPointerException: Attempt to invoke virtual method ‘void java.io.OutputStream.write(byte[])’ on a null object reference. The open button is working. I used 2 printer. 1 thermal printer and 1 dot matrix printer and both of the printer is not working. Can you help me? thank you.
It’s working ,, thanks a lot
How to print through WIFI ??
java.lang.NullPointerException: Attempt to invoke virtual method ‘void java.io.OutputStream.write(byte[])’ on a null object reference
THank you so much… its work for me… my model printer is ZJ-5802LD
Hi,
did anyone try to do something similar in App Inventor 2. i.e print some text from Android phone to a bluetooth thermal printer?
thanks in advance for any details.
hi ,
this is for the input text but i just want to print the whole data near about 2 page .Then for that please give me some code. with that i can print my dynamic data. if it is paid then tell me.
hi! I have a printer DPP 250, the program is working good.. and conncet whith the printebut the print does not come out! plis help
Excellent tutorial!
Is there anybody who is able explain that why used this uuid “00001101-0000-1000-8000-00805f9b34fb” ?
is this code work with POS printers ?
Hey how can I list the paired device on a builder and then when I click on a device it connect to the selected device?
how to set font??
Hello Friend! Do you have a code where I can increase the size of the character to be displayed? I have a small project here, but the default font size on the printer does not please the client …
Hello there, I have tried this source code (level 1), everything is working well until the part where I have to send Data to the printer. There the exception happens i.e. Java.IO.IOException: Broken pipe.
I have no idea what is wrong with it. I am trying to deploy this code in Xamarin C# Android.
Any help will be appreciated thanks.
Hello Mike , Great work ! Appreciate it . But I was wondering the way to do the same thing via a wifi printer. Will you be able to provide the way to scan the wifi printer and send the data to be printed? Hope to hear from you soon.
HI.
Trouble writing Persian text
PLZ HELP ME
thank you sooooo much, it’s also worked for me
Use Printooth library for any kind of printers and don’t tire yourself.
https://github.com/mazenrashed/Printooth
i want a wifi printing example
How do I change the font size and then send it to print?
THANK YOU..:)
Can possible to print in A4 size paper using Bluetooth??? how to set that dimension???
i dont know why it cant work . My Connected printer is star printer
android java.lang.nullpointerexception attempt to invoke virtual method ‘voidjava.io.outputstream.write(bytes[])on null object ref
getting this error
How to print value in listview with checkbox
How to print listview with checkbox
Hello
Need this code to run on Xamarin Forms,
Do you have it ?
In what place do I place the step 6?
Hello, Just copied this code and run. It shows the paired devices and shows “Bluetooth device found” in EditText field. Things worked well upto socket creation but on connect() call exception occurs like this ” read failed, socket might closed or timeout, read ret: -1 “. Please help !!!
Many thanks.
Your code works well in ESC/POS mode, but when I tested it in TPCL mode on my Toshiba B-EP4 DL, it also looks like send data to the printer, but it just doesn’t print anything.
I am trying to write an APP to print in TPCL mode. I have fount tens of code blocks that work well in ESC/POS but nothing to print in TPCL via Bluetooth.
I have already purchased a bluetooth printer from:https://www.amazon.in/HOIN-Certified-Bluetooth-Thermal-Receipt/dp/B07R958X1Y/ref=sr_1_5?dchild=1&keywords=bluetooth+printing+machine&qid=1591080914&sr=8-5
can this code work with this device?
Hi Lucifer, sorry, I haven’t tested the code with that device. I only tested it with the device mentioned above.
Hello There, i have bought your source code for Android Bluetooth Printing Source Code – LEVEL 2 Source Code on Code Ninja. Order ID#24989. I haven’t received any download link. Please send me the link.
Hi Kranthi, I re-sent the source code to your email. Please check.
Hi I just buy your source code, but I am new to android studio and it says need to change property about androidx how should i do it best regards,
Nathan
does this code works with the Zebra blutooth printer
What is the max height of an image we can print?
This was really helpful. It worked for me. Thanks
What about other european letters (example ščćžđ)?
Have problems with those
Hello. How is it possible to get UTF chars in android?
For example ščćžđ
Thanks
Hello, I am interested to buy the source, please let me know some details:
1. is there complete java source code in clear included, includine the source code of the library?
2. is there a list of supported BT printers?
3. does it works also with WiFi printers?
4. how can I purchase and how will I receive the source code?
5. does it print to 50mm and 80mm BT printers?
6. does it print Barcode & QR code?
Thank You.
Hello. Very good tutorial.
I have successfully implemented your code, but now I want to print a label in code39 barcode. Do you have the java code?
Thanks for your help. Greetings.
i want to learn your level 2 source code but i don’t have money
Tahnk you very much
You’re welcome! Glad you found our tutorial helpful. :)
Hello, I would like to buy this code. Is there any new updated version that I will get?
Is it possible to print many rows (restaurant bill) without buffer problems?
Leonardo, you can purchase the code, if it did not work, we will send you a refund.
Is this project still alive??
Hi there, yes, the code still works on my end.