一:无驱(通过ip连接打印机) String filePath = "D:\\file.pdf"; //需要打印的文件 String ip = "192.168.2.240"; //打印机ip I
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();
来源地址:https://blog.csdn.net/qq_63312957/article/details/132471563
--结束END--
本文标题: Java调用打印机两种方式(无驱/有驱)
本文链接: https://lsjlt.com/news/433331.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0