我想在我的应用程序中按下按钮并将 pdf 文档发送到打印机以直接打印(不显示来自打印框架 Android 4.4 的系统 android 预览)。我该怎么做? 我试图通过套接字连接到打印机。没问题,无一异常(exception),但我的打印机没有响应,也没有打印任何东西。
也许我需要在手机上为具体打印机设置驱动程序?但是如何做到这一点以及我在哪里可以获得这样的驱动程序?
已编辑
最佳答案
我编写了一个类来帮助将 PDF 文件直接打印到网络打印机,并提供其 IP。它应该适用于大多数打印机,只要它们支持 PJL 命令。
public class PrintService {
private static PrintListener printListener;
public enum PaperSize {
A4,
A5
}
public static void printPDFFile(final String printerIP, final int printerPort,
final File file, final String filename, final PaperSize paperSize, final int copies) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Socket socket = null;
DataOutputStream out = null;
FileInputStream inputStream = null;
try {
socket = new Socket(printerIP, printerPort);
out = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
inputStream = new FileInputStream(file);
byte[] buffer = new byte[3000];
final char ESC = 0x1b;
final String UEL = ESC + "%-12345X";
final String ESC_SEQ = ESC + "%-12345\r\n";
out.writeBytes(UEL);
out.writeBytes("@PJL \r\n");
out.writeBytes("@PJL JOB NAME = '" + filename + "' \r\n");
out.writeBytes("@PJL SET PAPER=" + paperSize.name());
out.writeBytes("@PJL SET COPIES=" + copies);
out.writeBytes("@PJL ENTER LANGUAGE = PDF\r\n");
while (inputStream.read(buffer) != -1)
out.write(buffer);
out.writeBytes(ESC_SEQ);
out.writeBytes("@PJL \r\n");
out.writeBytes("@PJL RESET \r\n");
out.writeBytes("@PJL EOJ NAME = '" + filename + "'");
out.writeBytes(UEL);
out.flush();
} catch (IOException e) {
e.printStackTrace();
if (printListener != null)
printListener.networkError();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (out != null)
out.close();
if (socket != null)
socket.close();
if (printListener != null)
printListener.printCompleted();
} catch (IOException e) {
e.printStackTrace();
if (printListener != null)
printListener.networkError();
}
}
}
});
t.start();
}
public static void setPrintListener(PrintListener list) {
printListener = list;
}
public interface PrintListener {
void printCompleted();
void networkError();
}
}
关于java - 在没有打印服务预览的情况下打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47937508/