怎么用java调用默认打印机打印文档?
发布网友
发布时间:2022-04-24 11:19
我来回答
共2个回答
热心网友
时间:2023-10-11 00:27
java实现调用默认打印机打印文档(以D盘.txt文档为例),代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
/**
* 调用打印机功能
* @author Administrator
**/
public class PrintDemoII {
public static void main(String[] args) {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService []pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200, pservices,
defaultService, flavor, aset);
if(service != null){
try {
DocPrintJob pj =service.createPrintJob();
FileInputStream fis = new FileInputStream("D:"+ File.separator +".txt");//打印D盘.txt文档。
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
pj.print(doc, aset);
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (PrintException e) {
e.printStackTrace();
}
}else {
System.out.println("打印失败");
}
}
}
热心网友
时间:2023-10-11 00:27
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
//设置打印格式,因为未确定文件类型,这里选择AUTOSENSE
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
//查找所有的可用打印服务
PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
//定位默认的打印服务
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//显示打印对话框
PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
if (service != null) {
try {
DocPrintJob job = service.createPrintJob(); //创建打印作业
FileInputStream fis = new FileInputStream(file); //构造待打印的文件流
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das); //建立打印文件格式
job.print(doc, pras); //进行文件的打印
}catch(Exception e) {
e.printStackTrace();
}
}