java调用打印机 兼容各种驱动版

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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值