21

在我的项目中需要通过蓝牙打印机打印 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

5 回答 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 Manifest 中添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
于 2015-12-21T12:47:47.603 回答
1

大多数蓝牙打印机不支持开箱即用打印 PDF。

您需要做的是使用 Android 打印机框架或任何其他库/类(如PDFRenderer)将 PDF 页面转换为图像,并将这些图像通过打印机理解的仿真(例如 ZPL、CPCL、PCL-3 等)发送到打印机。 )

于 2016-05-22T10:39:53.000 回答
1

任何打印 pdf 的应用程序都有一些库来解码 pdf。

当然,您只能向打印机发送文本。

如果您想直接打印 pdf,则需要您自己的库来执行此操作。

对于 android,我总是使用 mupdf,非常强大的 lib 和开源。

看看stackoverflow如何安装一步一步在应用程序中集成MuPDF阅读器

https://github.com/derek-watson/mupdf运行完整的演示项目后

目录列表(mupdf/platform/android/)

它将运行主要活动 ChoosePDFActivity.java 从您的设备中选择它将显示,然后主顶部栏有打印按钮(PrintDialogActivity.java 用于在谷歌云打印上打印)在此处更改代码以将流发送到您的打印机

希望这有帮助!!!

于 2015-12-19T18:20:58.370 回答
0

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

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
c.startActivity(intent);
于 2015-12-22T11:12:29.773 回答
0

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

于 2022-01-20T14:30:35.350 回答