通过蓝牙打印机在安卓设备上打印PDF文件

23

在我的项目中,需要通过蓝牙打印机打印PDF文件。我编写了一段代码来打印PDF文件,对于文本来说是好用的,但是我想要在蓝牙打印机上打印PDF文件。以下是我的Java代码来打印文本。

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

   }

我不知道如何将PDF文件传递给蓝牙打印机进行打印。

请帮助我,我该怎么做?

提前致谢。


4
联系打印机制造商并询问他们。地球上没有其他人能够帮助你。 - CommonsWare
你找到解决方案了吗?我也有相同的要求,请给予建议。 - jyomin
Google Cloud打印PDF仅支持API 19及以上版本。唯一的方法是通过编程生成PDF并保存在内部存储器中,然后尝试使用Intent Action Pick通过Google Cloud打印进行打印。在Android上无法即时打印PDF。 - Swaminathan V
5个回答

2
您可以尝试从PDF文件中获取字节,并按照以下方式将它们发送到打印机:
/*
 * 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();
}
}

您需要在Android清单中添加以下权限:

您需要在您的Android清单中添加以下权限:

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

@Amalo,请告诉我您是否遇到了上面代码的任何问题...我会帮助您解决! - Osama Mohammed Shaikh
我正在使用相同的代码,但是我无法获得原始文本,即:它以机器可读格式显示。您有任何解决方案吗? - dileep
在打印字符串值时,使用while循环。 - dileep
字符串 msg = myTextbox.getText().toString(); mmOutputStream.write(msg.getBytes()); mmOutputStream.flush(); - dileep
@dileep,你现在可以使用上面的代码打印文本了吗?我使用的是HP Officejet H470打印机,Android将数据发送到打印机,但打印机只是喷墨出空白纸。如果你有可用的代码或任何参考资料,请引导我一下。 - Farid
显示剩余4条评论

1
任何应用程序打印PDF都有一些库来解码PDF。
当然,您可以仅向打印机发送文本。
如果要直接打印PDF,则需要自己的库来完成此操作。
对于Android,我总是使用mupdf,这是一个非常强大的开源库。
请参阅stackoverflow,了解如何逐步安装Integrate MuPDF Reader in an app
安装完成后,请运行https://github.com/derek-watson/mupdf中的完整演示项目。
在目录中列出(mupdf/platform/android/)
选择PDF后,它将运行主活动ChoosePDFActivity.java,然后显示,然后主顶部栏有打印按钮(PrintDialogActivity.java可打印到Google Cloud打印机),在此更改代码以将流发送到打印机。
希望这有所帮助!

1
大多数蓝牙打印机默认不支持打印PDF文件。
您需要使用Android打印框架或任何其他库/类(如PDFRenderer)将PDF页面转换为图像,并使用打印机理解的仿真发送这些图像(例如ZPL,CPCL,PCL-3等)。

0

如果从另一个应用程序(也许是制造商自己的应用程序)打印PDF文件是可能的,您可以尝试使用Android意图打开它。

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

0

您可以让应用程序先将PDF静默转换为位图,然后通过热敏打印机打印位图。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接