SpringBoot系列---【java实现调用打印机】

1.准备工作

  要调用的电脑已经连上打印机,并且可以正常打印。

2.引入pom依赖

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.8</version>
</dependency>

3.Demo示例

复制代码
 @ApiOperation(value = "打印测试")
    @PostMapping("/print1")
    public void print(String printName,@RequestPart("multipartFile") MultipartFile multipartFile) throws IOException, PrinterException {
//        // 使用打印机的名称
//        String printName = "\\\\172.17.1.127\\Canon-print";
        
        /*
            保存上传的文件到"e:\\"
         */
//        String pdfPath = "e:\\";
//        File file = new File(pdfPath+headerImg.getOriginalFilename());
//        InputStream inputStream = headerImg.getInputStream();
//        FileOutputStream out = new FileOutputStream(file);
//        IoUtil.copy(headerImg.getInputStream(),out);
//        out.write(headerImg.getBytes());
//        out.close();

        // 读取pdf文件
        PDDocument document = PDDocument.load(multipartFile.getInputStream());
        // 创建打印任务
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setJobName(multipartFile.getOriginalFilename());
        // 遍历所有打印机的名称
        for (PrintService ps : PrinterJob.lookupPrintServices()) {
            String psName = ps.toString();
            // 选用指定打印机
            if (psName.equals(printName)) {
                job.setPrintService(ps);
                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();
    }
复制代码

 

posted on   少年攻城狮  阅读(5190)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示