简体   繁体   English

"通过蓝牙打印机 Android 打印 Pdf 文件"

[英]Print Pdf file via Bluetooth Printer Android

In My project Need to print Pdf file Via Bluetooth Printer.在我的项目中需要通过蓝牙打印机打印 Pdf 文件。 I write a code to print via pdf Its for fine for a Text,我编写了一个代码以通过pdf打印它对于文本来说很好,

But I want to Print PDF file on Bluetooth printer.但我想在蓝牙打印机上打印 PDF 文件。

My java Code to Print Text我的 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();
     }

   }

I don't have Idea How to Pass Pdf file for print to Bluetooth Printer我不知道如何将 Pdf 文件传递​​给蓝牙打印机进行打印

Please Help Me How i can do this请帮帮我我该怎么做

Thanks In Advance.提前致谢。

You could try getting bytes from a pdf file & send them to printer as follows: 您可以尝试从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();
}
}

You will need to add following permissions in your Android Manifest: 您需要在Android Manifest中添加以下权限:

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

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?) 您可以尝试使用Android意图打开pdf,如果可以从其他应用程序打印它(可能是制造商自己的?)

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

Most bluetooth printers do not support printing PDFs out of the box. 大多数蓝牙打印机不支持打印PDF。

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.) 您需要做的是使用Android打印机框架或任何其他库/类(如PDFRenderer)将PDF页面转换为图像,并使用打印机能够识别的仿真将这些图像发送到打印机(例如ZPL,CPCL,PCL-3等。 )

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

Any application print a pdf has some library to decode pdf. 任何应用程序打印pdf都有一些库来解码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. 如果你想直接打印pdf,你需要自己的库来做到这一点。

For android i always use mupdf, very powerfuf lib and open source. 对于android我总是使用mupdf,非常强大的lib和开源。

look at stackoverflow how to install step-by-step Integrate MuPDF Reader in an app 看看stackoverflow如何逐步安装在应用程序中集成MuPDF Reader

after you done run a full demo project from https://github.com/derek-watson/mupdf 完成后,从https://github.com/derek-watson/mupdf运行完整的演示项目

list on directory (mupdf/platform/android/) 目录上的列表(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 它将从您将显示的设备中选择pdf后运行主要活动ChoosePDFActivity.java,然后主顶部栏具有打印按钮(PrintDialogActivity.java以在Google云打印上打印)更改此处的代码以将流发送到您的打印机

Hope this help!!! 希望这有帮助!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM