一:无驱(通过ip连接打印机)
String filePath = "D:\\file.pdf"; //需要打印的文件String ip = "192.168.2.240"; //打印机ipInteger 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.pdfboxpdfbox2.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 formatPageFormat pageFormat = new PageFormat();pageFormat.setPaper(paper);// override the page formatBook book = new Book();// append all pages 设置一些属性 是否缩放 打印张数等book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, pageCount);job.setPageable(book);// 开始打印job.print();//创建打印任务document.close();