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

2024-03-24

在我的项目中需要通过蓝牙打印机打印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 清单中添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过蓝牙打印机 Android 打印 Pdf 文件 的相关文章

随机推荐

  • Clojure中,函数、引用函数和尖引号函数之间的区别

    在 clojure 中 我想知道以下三者之间有什么区别 println map 1 2 3 4 5 6 println map 1 2 3 4 5 6 println map 1 2 3 4 5 6 结果是 5 7 9 4 5 6 5 7
  • 如何将 Express 响应对象传递给前端 JS 对象

    我的控制器正在通过 res render 将纬度 经度数据发送到我的车把视图 res render coords viewModel viewModel 包含一个对象数组 每个对象都包含位置名称 纬度和经度 我想获取这些信息并在我的视图中的
  • Google Play 控制台显示 Release not live

    通常 当应用程序在内部渠道中发布时 构建会立即得到反映 一分钟之内 但奇怪的是 即使一天后 构建也没有反映出来 我正在使用最新的 Google 控制台 其状态显示为 发布未上线 而不是 正在审核 您能帮助了解可能导致此情况的行为或情况吗 当
  • 在 Phonegap Build App (iOS/Android) 中打开外部链接

    我在用着音隙构建要部署 mi Apps 我正在使用科尔多瓦3 3 0版本 我想在本机浏览器中打开外部链接 安卓 iOS 我正在尝试使用InAppBrowser 插件科尔多瓦 但这对我不起作用 打开链接 但在应用程序内没有后退按钮 我见过这样
  • LDAP C++ API 选择 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我想在 Linux 下编写自己的 LDAP 客户端 特定于我们的本地环境 我很可能会使用 QT4 来提
  • 如何获取 MongoDB 集合中的最后一项?

    我有时使用 MongoDB 来执行各种快速插入或作为日志 但我在获取非常简单的查询 在 Mongo 中 我该如何获得类似于此 T SQL 的结果 SELECT TOP 1 date FROM Collection ORDER BY date
  • C++ 的 NumPy 风格数组? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 是否有任何 C 或 C 库具有类似 NumPy 的数组 支持切片 向量化操作 逐个元素添加和减去内容等
  • 为什么最好的做法是用括号将分配给变量的 JSX 括起来?

    在下面的示例中 x 和 y 的输出相同 我见过两种方式编写的 React 代码 有区别吗 由于我看到的许多 React 代码示例都使用括号语法 我认为这是有原因的 如果这是最佳实践 那么为什么用括号将分配给变量的 JSX 括起来是最佳实践
  • 如何存储大量数据?

    我必须 在状态机上 制作 RSA 签名C在 32 位板上 我的内存有限 所以我无法将小数存储在向量或类似的东西中 最好的事情是如果我可以存储位并且可以轻松访问它们 什么存储方法最好 我做了这个 if CPU TYPE CPU TYPE 32
  • 通过 PHP 的 JS 解包器 - 函数(p,a,c,k,e,r)

    我在互联网上搜索但到目前为止没有找到解决方案 我必须抓取用以下内容压缩的页面 具有视频流 的内容Dean Edwards 封隔器工具 http dean edwards name packer 实时 因此 我只需要通过 PHP 来解码压缩的
  • 通过 Java 执行 ADS 相关的 Powershell 命令不起作用,使用 2 种不同的方式时会出现 2 种不同的错误

    我一直在尝试通过 java 在 powershell 会话中执行一组命令 但还没有成功 我的目标是在 AD 中搜索域为 domain com 的计算机对象 我从一个命令开始 不幸的是 以下命令在我的 powershell 提示符下成功运行
  • 图像不显示在 jar 中但显示在编译器中?

    我知道 我知道 这个问题以前有人问过 但我看过的每个资源都使用 IconImages 而我只有普通图像 有不同的解决方案吗 请帮助 因为我已经坚持研究并试图解决这个问题好几天了 但没有任何进展 Image Floor Toolkit get
  • 何时使用块

    我喜欢红宝石块 它们背后的想法非常非常简洁和方便 我刚刚回顾了过去一周左右的代码 基本上是我写过的每一个 ruby 函数 而且我注意到它们中没有一个返回值 我总是使用块来传回数据 而不是返回值 我什至发现自己正在考虑编写一个小状态类 这将允
  • 如何在ubuntu 15.04中安装poppler?

    Poppler 是一个基于 xpdf 3 0 代码库的 PDF 渲染库 我已经从官方网站下载了 tar xz 文件http poppler freedesktop org http poppler freedesktop org 但我不知道
  • 从另一个范围中的值定义一个范围

    我有一个 Excel 文件 其中包含已完成或未完成的任务 并在列中用 是 或 否 表示 最终 我对不同列中的数据感兴趣 但我想设置代码 以便它忽略任务已完成的那些行 到目前为止 我已经定义了包含是 否的列范围 但我不知道在此范围上运行哪个命
  • C# 中的通用 Func<> 类型

    我正在用 C 编写一个小型 Lisp 解释器 它基本上已经可以工作了 目前我正在使用一个接口来表示函数 public interface LispFunction object Apply ArrayList parameters 该接口由
  • 如何在 pygame 中有效地遮盖表面

    我按照建议掩盖 pygame 中的表面nkorth https stackoverflow com users 685933 nkorth回答问题有没有办法只在掩码中进行位块传输或更新 https stackoverflow com a 1
  • 我什么时候应该使用 stdClass,什么时候应该在 php oo 代码中使用数组?

    在工作中的大规模重构期间 我希望引入 stdClass 作为从函数返回数据的一种方式 并且我正在尝试找到非主观论据来支持我的决定 在什么情况下最好使用其中一种而不是另一种 使用 stdClass 而不是数组有什么好处 有人会说函数必须尽可能
  • 降低滚动视图中平滑滚动的速度[重复]

    这个问题在这里已经有答案了 我有一个滚动视图 我执行 smooth scroll using smoothScrollBy 一切正常 但我想更改平滑滚动的持续时间 平滑滚动发生得非常快 用户不明白发生了什么 请帮助我降低平滑滚动速度 简单的
  • 通过蓝牙打印机 Android 打印 Pdf 文件

    在我的项目中需要通过蓝牙打印机打印Pdf文件 我写了一个代码通过pdf打印 它对于文本来说很好 但我想在蓝牙打印机上打印PDF文件 我的打印文本的java代码 Override public void onCreate Bundle sav