一:无驱(通过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();
}
二:有驱(使用电脑自带驱动连接打印机)
添加依赖文章来源地址https://www.toymoban.com/news/detail-770672.html
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
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://www.toymoban.com/news/detail-770672.html
到了这里,关于Java调用打印机两种方式(无驱/有驱)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!