Imprimir archivo PDF a través de Bluetooth Impresora Android

En Mi proyecto Necesita imprimir el archivo Pdf a través de la impresora Bluetooth. Escribo un código para imprimir a través de pdf Su para bien para un texto,

Pero quiero imprimir el archivo del pdf en la impresora de Bluetooth.

Mi código java para imprimir texto

@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(); } } 

No tengo Idea Cómo pasar el archivo Pdf para la impresión a la impresora de Bluetooth

Por favor, ayúdame ¿Cómo puedo hacer esto

Gracias por adelantado.

Usted podría tratar de abrir el pdf usando una intención de Android si es posible imprimirlo desde otra aplicación (tal vez el propio fabricante?)

 Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/pdf"); c.startActivity(intent); 

Usted podría tratar de obtener bytes de un archivo pdf y enviarlos a la impresora de la siguiente manera:

 /* * 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(); } } 

Deberá agregar los siguientes permisos en su manifiesto de Android:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

La mayoría de las impresoras bluetooth no son compatibles con la impresión de archivos PDF fuera de la caja.

Lo que debe hacer es utilizar el marco de la impresora de Android o cualquier otra biblioteca / clase como PDFRenderer para convertir las páginas PDF en imágenes y enviar esas imágenes a la impresora con una emulación que la impresora entiende (por ejemplo, ZPL, CPCL, PCL-3 etc. )

Cualquier aplicación de impresión pdf tiene alguna biblioteca para decodificar pdf.

Por supuesto, sólo puede enviar un texto a su impresora.

Si desea imprimir directamente en pdf necesita su propia biblioteca para hacer eso.

Para android siempre uso mupdf, muy powerfuf lib y código abierto.

Mira stackoverflow cómo instalar paso a paso Integre MuPDF Reader en una aplicación

Después de ejecutar un proyecto completo de demostración de https://github.com/derek-watson/mupdf

Lista en el directorio (mupdf / platform / android /)

Se ejecutará la actividad principal ChoosePDFActivity.java después de que recogió el pdf de su dispositivo se mostrará, a continuación, la barra superior principal tiene botón de impresión (PrintDialogActivity.java para imprimir en google nube de impresión) cambiar el código aquí para enviar flujo a su impresora

¡¡¡Espero que esto ayude!!!

  • Conexión a un dispositivo HID bluetooth (ratón) mediante L2CAP
  • Android - ¿Cómo habilitar Bluetooth para estar siempre encendido?
  • Reemplazo de startLeScan a api actual
  • ¿Existe alguna manera de conectarse a un dispositivo Bluetooth Low Energy bajo Android 5 exponiendo la dirección estática pública?
  • ¿Podría crear más de un canal RFCOMM por hora?
  • Bluetooth "fuera de banda" (OOB) en el par de Android?
  • Cómo cambiar el tamaño de la fuente mientras se imprime en android?
  • Señal fatal 11 SIGSEGV al cerrar BluetoothSocket en Android 4.2.2 y 4.3
  • Bluetooth en el fondo como un servicio en Android?
  • ¿Cómo unpair o suprimir el dispositivo bluetooth apareado programmatically en androide?
  • Enrutamiento de audio a auriculares Bluetooth (no A2DP) en Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.