Java调用打印机两种方式(无驱/有驱)

一:无驱(通过ip连接打印机)

        String filePath = "D:\\file.pdf"; //需要打印的文件
        String ip = "192.168.2.240"; //打印机ip
        Integer port = 9100; // 打印机端口
        Integer timeout = 3000; //连接超时时间
        File file = new File(filePath); 
        Socket socket = new Socket(); 
        try {
            socket.connect(new InetSocketAddress(ip,port), timeout);
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            System.out.println(file.length());
            //建立数组
            byte[] buf = new byte[1024];
            int len = 0;
            //判断是否读到文件末尾
            while((len = fis.read(buf)) != -1)
            {
                out.write(buf, 0, len);
            }
            //告诉服务端,文件已传输完毕
            socket.shutdownOutput();
            socket.close();
            fis.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

二:有驱(使用电脑自带驱动连接打印机) 

添加依赖

        
            org.apache.pdfbox
            pdfbox
            2.0.8
        
        String filePath = "D:\\file.pdf"; //需要打印的文件
        File file = new File(filePath); 
        int pageCount = 0;
        String printName = "Win32 Printer : HP LaserJet Pro M428f-M429f [F097F8]";
        PrinterJob job = PrinterJob.getPrinterJob();
        // 遍历所有打印机的名称
        for (PrintService ps : PrinterJob.lookupPrintServices()) {
            String psName = ps.toString();
            // 选用指定打印机
            if (psName.equals(printName)) {
                job.setPrintService(ps);
                break;
            }
        }

        // 读取pdf文件
        PDDocument document = null;
        try {
            document = PDDocument.load(file);
            pageCount = document.getNumberOfPages();
        } catch (IOException e) {
            e.printStackTrace();
        }
        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, pageCount);
        job.setPageable(book);
        // 开始打印
        job.print();
        //创建打印任务
        document.close();

你可能感兴趣的:(java,开发语言,spring,boot)