Using a ByteArrayInputStream
throws java.lang.IllegalArgumentException
, but a regular byte array worked for me. Modifying the example of Ravinder Reddy:
// Get default print service
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
// Create a print job
DocPrintJob printJob = printService.createPrintJob();
// Optional fancy listener
printJob.addPrintJobListener(new PrintJobAdapter() {
@Override
public void printJobCompleted(PrintJobEvent pje) {
System.out.println("PDF printing completed");
super.printJobCompleted(pje);
}
@Override
public void printJobFailed(PrintJobEvent pje) {
System.out.println("PDF printing failed");
super.printJobFailed(pje);
}
});
// Check the PDF file and get a byte array
File pdfFile = new File("path/to/pdf");
if (pdfFile.exists() && pdfFile.isFile()) {
byte[] PDFByteArray = Files.readAllBytes(FileSystems.getDefault().getPath(pdfFile.getAbsolutePath()));
// Create a doc and print it
Doc doc = new SimpleDoc(PDFByteArray, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
printJob.print(doc, null);
}