Print Pdf file via Bluetooth Printer Android

13,730

Solution 1

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

Solution 2

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

Solution 3

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

Share:
13,730

Related videos on Youtube

user2624301
Author by

user2624301

Updated on June 29, 2022

Comments

  • user2624301
    user2624301 about 2 years

    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.

    • CommonsWare
      CommonsWare about 10 years
      Contact the printer manufacturer and ask them. Nobody else on the planet can help you.
    • jyomin
      jyomin almost 9 years
      Have you found the solution? I also have the same requirement..Please suggest
    • Swaminathan V
      Swaminathan V over 8 years
      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.
  • Osama Mohammed Shaikh
    Osama Mohammed Shaikh over 8 years
    @Amalo please let me know if you are facing any issue with the above code... I'll help you out!
  • dileep
    dileep over 8 years
    i am using the same code but i was not able to get original text ie: its shown in machine readable format do u have any solution for this sinario
  • Osama Mohammed Shaikh
    Osama Mohammed Shaikh over 8 years
    @dileep You mean you are getting machine readable text while printing the pdf file?
  • dileep
    dileep over 8 years
    while printing just string value
  • Osama Mohammed Shaikh
    Osama Mohammed Shaikh over 8 years
    @dileep can you please show me your relevant code so that I can see where you are going wrong? Just paste the relevant code in the comment...
  • dileep
    dileep over 8 years
    String msg = myTextbox.getText().toString(); mmOutputStream.write(msg.getBytes()); mmOutputStream.flush();
  • Osama Mohammed Shaikh
    Osama Mohammed Shaikh over 8 years
  • Farid
    Farid over 7 years
    @dileep, You're able to print text with code above yet? I'm using HP Officehjet H470, Android sends data to printer, what printer does is just ejecting blank page. If you have working code or any reference please redirect me to.
  • kartheeki j
    kartheeki j over 5 years