Reputation: 45
I have a problem, what happens is I want to send to print a file at a printer, for which I get the IP address of the printers I have networked and choose the first, here is the code for this:
PrintService[] service = PrinterJob.lookupPrintServices();// list of ip address
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintService(service[0]);//I get the first address
But now I want to assign the string that contains the IP address:\\10.100.20.26\My printer
of the printer that I want, and not the network that I have, and it is there that do not know how , someone please help me, I've searched for the solution, but I have not had good results.
Upvotes: 1
Views: 3631
Reputation: 307
public void printFile(File file, String printerIp) throws PrintException, IOException {
Socket socket = new Socket(printerIp, 9100);
FileInputStream fileInputStream = new FileInputStream(file);
byte [] mybytearray = new byte [(int)file.length()];
fileInputStream.read(mybytearray,0,mybytearray.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(mybytearray,0,mybytearray.length);
//Curious thing is that we have to wait some time to make more prints.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
outputStream.flush();
outputStream.close();
socket.close();
fileInputStream.close();
}
//void main
File f = new File("C:\\Users\\SHINWAR\\Desktop\\link.txt");
try {
printFile(f, "192.168.1.100"); //f : file to print , ip printer
} catch (Exception e) {
System.out.println(e + "--file");
}
print from ip and send file .txt
Upvotes: 0
Reputation: 23802
I am guessing that the PrintService
has some property that give you its path. So go over the array of PrintService
s to find one that matches the path you have and use it:
PrintService[] services = PrinterJob.lookupPrintServices();// list of ip address
String myPrinter = "10.100.20.26\My printer";
PrintService serviceToUse = null;
for (PrintService service: services) {
if (service.getPath().equals(myPrinter)) {
serviceToUse = service;
break;
}
}
if (serviceToUse != null) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintService(serviceToUse);
}
Upvotes: 1