22
votes

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.

4
Contact the printer manufacturer and ask them. Nobody else on the planet can help you.CommonsWare
Have you found the solution? I also have the same requirement..Please suggestjyomin
google cloud printing PDF is supported from API 19 and above only. The only way you can do is, generate the PDF programmatically and save in the internal memory . Then try to print using google cloud printing via Intent Action Pick . On the fly you cannot print the PDF in Android.Swaminathan V

4 Answers

3
votes

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" />
1
votes

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);
0
votes

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!!!

0
votes

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.)