打印机
package hyi.pos;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
public class PrintServiceTest4 {
public static void main(String[] args){
//1.新建打印任务
JFileChooser jFileChooser=new JFileChooser();
//2.选择文件的对话框
int state=jFileChooser.showOpenDialog(null);
//3.判断对话状态,用户选择了文件
if (state==jFileChooser.APPROVE_OPTION){
//4.获取选择的将要打印的文件对象
File file=jFileChooser.getSelectedFile();
//5.设置打印机指令集
HashPrintRequestAttributeSet pras=new HashPrintRequestAttributeSet();
//6.设置文件打印格式
DocFlavor docFlavor=DocFlavor.INPUT_STREAM.AUTOSENSE;
//7.查找本机所有打印服务(参数=打印格式,打印机属性指令集)
PrintService[] printServices=PrintServiceLookup.lookupPrintServices(docFlavor,pras);
//8.查找默认打印服务
PrintService printService=PrintServiceLookup.lookupDefaultPrintService();
//将要调用打印机的弹出框
PrintService uiPrintService=ServiceUI.printDialog(null,200,200,printServices,printService,docFlavor,pras);
if (uiPrintService!=null){
try {
//1.建立打印作业
DocPrintJob docPrintJob = uiPrintService.createPrintJob();
//2.流关联[将要打印的文件对象]
FileInputStream fileInputStream = new FileInputStream(file);
//3.文件打印指令集
DocAttributeSet docAttributeSet=new HashDocAttributeSet();
//文件对象 流 文本格式 文本指令
Doc doc=new SimpleDoc(fileInputStream,docFlavor,docAttributeSet);
//开始打印
docPrintJob.print(doc,pras);
}catch (Exception e){
e.printStackTrace();
} }
}
}
}