Java print pdf doesn't work

1.2k views Asked by At

I'm trying to print a PDF file with my local printer. The Problem is when I select the printer in the printer dialog and press the print button nothing happens, the dialog just closes. I don't get any Exceptions or Warnings, the printer is just not printing the PDF file. I don't know why this happens. I already tested it with three different Computers (Windows 7 & 10) and three different printers but always the same problem.

I also tried it with the PDFBox library like this:

try{
    FileInputStream fis = new FileInputStream("C:/Users/Self/Desktop/test.pdf");
    PDDocument doc = new PDDocument();
    doc.load(fis);
    doc.print();
}catch(FileNotFoundException ex1){
    ex1.printStackTrace();
}catch(IOException ex2){
    ex2.printStackTrace();
}catch(PrinterException ex3){
    ex3.printStackTrace();
}

and with the standard java way like this:

DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor,  aset);
if(ps.length == 0){
    throw new IllegalStateException("No Printer found");
}
PrintService myService = null;
for (PrintService printService : ps) {
    if (printService.getName().equals("HP17DC1C (HP Officejet Pro 8610)")) { 
        myService = printService;
        break;
    }
}

if (myService == null) {
    throw new IllegalStateException("Printer not found");
}

try{
    FileInputStream fis = new FileInputStream("C:/Users/Slef/Desktop/test.pdf");
    Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    DocPrintJob printJob = myService.createPrintJob();
    printJob.print(pdfDoc, aset);
    fis.close(); 
}catch(FileNotFoundException ex1){
    ex1.printStackTrace();
}catch(PrintException ex2){
    ex2.printStackTrace();
}catch(IOException ex3){
    ex3.printStackTrace();
}

but both ways lead to the same problem. After the print dialog nothing happens. I'm using java version 8.66. Can anyone help me with this problem, I really need to print PDF files?

0

There are 0 answers