Reputation: 3429
I am trying to print a PDF document.
I can see the job in the printer queue, and then I see it disappear, like if the printer had finished its job.
But the problem is that nothing is printing. I can't figure out what is wrong in my code.
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null,null);
PrintService service = null;
for (String imprimante : listImprimantes){
for( PrintService printService : printServices ) {
Attribute[] attrs = printService.getAttributes().toArray();
for (int j=0; j<attrs.length; j++) {
String attrName = attrs[j].getName();
String attrValue = attrs[j].toString();
if (attrName.equals("printer-info")){
if (attrValue.equals(imprimante)){
service = printService;
DocFlavor[] flavors = service.getSupportedDocFlavors();
break;
}
}
}
}
}
InputStream fi = new ByteArrayInputStream(baos.toByteArray());
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob printJob = service.createPrintJob();
Doc doc = new SimpleDoc(fi, flavor, null);
try {
if (doc != null) {
printJob.print(doc, null);
}
}
catch (PrintException e1) {
log.debug(e1.getMessage());
}
If anyone can help me on this...
Upvotes: 3
Views: 3597
Reputation: 881
I know it is a bit late to answer but since I had the same problem I think it can help others to post my solution.
I have faced this problem on Windows (7), but not on Linux (Fedora), so my first action was to check the drivers setup.
Then, I saw that PDFs are not native processed by many printers. It is accepted but nothing is printed. From this, several solutions can be chosen:
I chose solution 2 and it works like a charm. The nice thing in this is that it also uses PrintService, with attributes, so you can deal with pages, printer trays and many options.
Here is a part of my code:
private boolean print(PrintService printService, InputStream inputStream, PrintRequestAttributeSet attributes)
throws PrintException {
try {
PDDocument pdf = PDDocument.load(inputStream);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
} catch (PrinterException e) {
logger.error("Error when printing PDF file using the printer {}", printService.getName(), e);
throw new PrintException("Printer exception", e);
} catch (IOException e) {
logger.error("Error when loading PDF from input stream", e);
throw new PrintException("Input exception", e);
}
return true;
}
Hope this helps.
Upvotes: 2