public static ResultData JPGPrint(PrintParamVO printParamVO) throws Exception {// 默认为A4纸张,对应像素宽和高分别为 595, 842double 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();
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!