在Java中,可以使用Java Print Service API(javax.print包)來連接和打印機進行交互。以下是一個簡單的示例,演示如何使用Java連接到打印機并打印文本:
首先,確保已經安裝了打印機驅動程序,并在操作系統中正確設置了打印機。
創建一個Java項目,并導入以下所需的庫:
import java.io.ByteArrayInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
public void printText(String printerName, String textToPrint) {
try {
// 查找指定名稱的打印機
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
PrintService selectedPrinter = null;
for (PrintService printService : printServices) {
if (printService.getName().equalsIgnoreCase(printerName)) {
selectedPrinter = printService;
break;
}
}
if (selectedPrinter == null) {
System.out.println("未找到指定的打印機: " + printerName);
return;
}
// 創建要打印的文檔
DocFlavor docFlavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
byte[] textBytes = textToPrint.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(textBytes);
Doc doc = new SimpleDoc(inputStream, docFlavor, null);
// 創建打印請求屬性集
PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
// 創建打印作業
DocPrintJob printJob = selectedPrinter.createPrintJob();
// 打印文檔
printJob.print(doc, attributeSet);
System.out.println("文本已成功發送到打印機: " + printerName);
} catch (Exception e) {
e.printStackTrace();
}
}
printText
方法,傳入打印機名稱和要打印的文本:public static void main(String[] args) {
String printerName = "Your Printer Name"; // 將此處替換為實際打印機名稱
String textToPrint = "Hello, World!";
printText(printerName, textToPrint);
}
注意:請確保將printerName
變量替換為實際打印機的名稱。這個示例將文本作為字節數組輸入流發送給打印機,因此它應該適用于大多數打印機。根據打印機的功能和需求,您可能需要修改此示例以適應特定的打印任務。