2017-12-25 【java】实现打印功能
来源:互联网 发布:上海专业seo 编辑:程序博客网 时间:2024/05/16 10:32
引自【阿甘1976】的回答:点击打开链接
public String printReport() { FileInputStream textStream = null; try { textStream = new FileInputStream("D:\\1.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } //String printStr = "打印测试内容";// 获取需要打印的目标文本 if (textStream != null) // 当打印内容不为空时 { // 指定打印输出格式 DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;//SERVICE_FORMATTED.PRINTABLE PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); // 设置纸张大小,也可以新建MediaSize类来自定义大小 pras.add(MediaSizeName.ISO_A4); //可用的打印机列表(字符串数组) PrintService printServices[] = PrintServiceLookup.lookupPrintServices(flavor, pras); // 定位默认的打印服务 PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); // 创建打印作业 DocPrintJob job = printService.createPrintJob(); DocAttributeSet das = new HashDocAttributeSet(); // 指定打印内容 Doc doc = new SimpleDoc(textStream, flavor, das); // 不显示打印对话框,直接进行打印工作 try { job.print(doc, pras); // 进行每一页的具体打印操作 } catch (PrintException pe) { pe.printStackTrace(); } } else { // 如果打印内容为空时,提示用户打印将取消 JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); } return ajax(Status.success, "success"); }
阅读全文