Java PDF printing: job sent to print job queue but not printing anything

I am trying to print a pdf document.
I see the work in the printer queue, and then I see that it disappears, for example, if the printer has finished work.

But the problem is that nothing is printed. I can not understand 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 with this ...

+2
source share
1 answer

I know it’s a little late to answer, but since I had the same problem, I think this can help others post my solution.

I ran into this problem on Windows (7), but not Linux (Fedora), so my first step was to check the driver settings.

Then I saw that PDF files are not proprietary, processed by many printers. This is accepted, but nothing is printed. Several solutions can be selected from this:

  • Convert PDF to PS or something like that before sending it to the printer.
  • Use a third-party library, such as Apache PdfBox (current version 2.0.2).

I chose solution 2 and it works like a charm. The best part is that it also uses a PrintService with attributes, so you can handle pages, trays for the printer, and many options.

Here is 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.

+1
source

Source: https://habr.com/ru/post/1391800/


All Articles