java中使用Ireport生成jrxml模版 根据模版连接打印机打印

主要思路就是先把jrxml文件转成PDF格式并生成,再通过PrinterJob连接到打印机进行打印操作。

总体来说在使用中还是踩过很多坑的。欢迎有问题一起探讨,有更好的实现方法也望不吝赐教。

下面是源码

public void test() {
        try {
            // 加载JRXML文件
            Resource resource = new ClassPathResource("OneCodeByTraceId.jrxml");
            InputStream inputStream = resource.getInputStream();

            // 1. 加载报表模板
            JasperReport report = JasperCompileManager.compileReport(inputStream);

            List<Map<String, Object>> data = new ArrayList<>();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("TRACE_ID", "T123465789");
            data.add(dataMap);

            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(data);
            JasperPrint print = JasperFillManager.fillReport(report, null, dataSource);

            String pdfPath = "D:\\quietPrint.pdf";
            JasperExportManager.exportReportToPdfFile(print,pdfPath);

            File file = new File(pdfPath);
            // 读取pdf文件
            PDDocument document = null;
            try {
                document = PDDocument.load(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 创建打印任务
            PrinterJob job = PrinterJob.getPrinterJob();
            String printerName = "HP LaserJet Professional M1216nfh MFP";
            // 遍历所有打印机的名称
            for (PrintService ps : PrinterJob.lookupPrintServices()) {
                String psName = ps.toString();
                // 选用指定打印机
                if (psName.equals(printerName)) {
                    try {
                        job.setPrintService(ps);
                    } catch (PrinterException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }

            job.setPageable(new PDFPageable(document));

            Paper paper = new Paper();
            // 设置打印纸张大小
            paper.setSize(598, 842); // 1/72 inch
// 设置打印位置 坐标
            paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
// custom page format
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(paper);
// override the page format
            Book book = new Book();
// append all pages 设置一些属性 是否缩放 打印张数等
            book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, 1);
            job.setPageable(book);
// 开始打印
            job.print();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值