[英]Print Pdf file via Bluetooth Printer Android
在我的項目中需要通過藍牙打印機打印 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 文件傳遞給藍牙打印機進行打印
請幫幫我我該怎么做
提前致謝。
您可以嘗試從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" />
您可以嘗試使用Android意圖打開pdf,如果可以從其他應用程序打印它(可能是制造商自己的?)
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
c.startActivity(intent);
大多數藍牙打印機不支持打印PDF。
您需要做的是使用Android打印機框架或任何其他庫/類(如PDFRenderer)將PDF頁面轉換為圖像,並使用打印機能夠識別的仿真將這些圖像發送到打印機(例如ZPL,CPCL,PCL-3等。 )
您可以讓應用程序先將 PDF 靜默轉換為位圖,然后通過熱敏打印機打印位圖。
任何應用程序打印pdf都有一些庫來解碼pdf。
當然,您只能向打印機發送文本。
如果你想直接打印pdf,你需要自己的庫來做到這一點。
對於android我總是使用mupdf,非常強大的lib和開源。
看看stackoverflow如何逐步安裝在應用程序中集成MuPDF Reader
完成后,從https://github.com/derek-watson/mupdf運行完整的演示項目
目錄上的列表(mupdf / platform / android /)
它將從您將顯示的設備中選擇pdf后運行主要活動ChoosePDFActivity.java,然后主頂部欄具有打印按鈕(PrintDialogActivity.java以在Google雲打印上打印)更改此處的代碼以將流發送到您的打印機
希望這有幫助!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.