public static ResultData JPGPrint(PrintParamVO printParamVO) throws Exception { // 默认为A4纸张,对应像素宽和高分别为 595, 842 double width = Integer.parseInt(printParamVO.getWidths()) * 2.8; double height = Integer.parseInt(printParamVO.getHeights()) * 2.8; Float x = Float.valueOf(printParamVO.getLefts()); Float y = Float.valueOf(printParamVO.getTops()); // 通俗理解就是书、文档 Book book = new Book(); // 设置成竖打 PageFormat pf = new PageFormat(); pf.setOrientation(PageFormat.PORTRAIT); // 通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。 Paper p = new Paper(); p.setSize(width,height);//纸张大小 p.setImageableArea(x,y, width,height);//打印区域 pf.setPaper(p); // 把 PageFormat 和 Printable 添加到书中,组成一个页面 book.append((graphics, pageFormat, pageIndex) -> {//通过一个匿名内部内实现Printable接口,不懂的自行查看jdk8的新特性 try { //远程图片url转成文件流 URL url= new URL(printParamVO.getFileUrl()); //也可以通过file构建一个本地图片File对象传递给ImageIO.read()方法 BufferedImage image= (BufferedImage)ImageIO.read(url); //将图片绘制到graphics对象中(为什么把需要打印的内容drawImage就可以实现打印自己取看值传递一引用传递的区别) graphics.drawImage(image,Convert.toInt(x),Convert.toInt(y), Convert.toInt(width),Convert.toInt(height),null); } catch (Exception e) { e.printStackTrace(); } return 0; }, pf); // 获取打印服务对象 PrinterJob job = PrinterJob.getPrinterJob(); //打印的数量 job.setCopies(printParamVO.getPrintNum()); // 设置打印类 job.setPageable(book); // 定位打印服务 PrintService printService = null; if (printParamVO.getPrintName() != null) { //获得本台电脑连接的所有打印机 PrintService[] printServices = PrinterJob.lookupPrintServices(); if (printServices == null || printServices.length == 0) { System.out.print("打印失败,未找到可用打印机,请检查。"); throw new CommonException("500", "打印失败,未找到可用打印机,请检查。"); } //匹配指定打印机 for (int i = 0; i < printServices.length; i++) { System.out.println(printServices[i].getName()); if (printServices[i].getName().equals(printParamVO.getPrintName())) { printService = printServices[i]; break; } } if (printService == null) { throw new CommonException("500", "打印失败,未找到打印机,请检查。"); } } job.setPrintService(printService); job.print(); return ResultData.success(); }
10-18
1291
01-13
04-11
5570