PDFBox: How to print pdf with specified printer?

后端 未结 5 946
余生分开走
余生分开走 2020-12-14 10:32

I want to use PDFBox for printing PDF files created by iText. I have tried this successfully with PDDocument class and its method print(). You can find docu

5条回答
  •  情歌与酒
    2020-12-14 10:43

    You can use the setPrintService() method on the PrinterJob Object.

    public static void main(String args[]) throws Exception {
    
        PDDocument document = PDDocument.load(new File("C:/temp/example.pdf"));
    
        PrintService myPrintService = findPrintService("My Windows printer Name");
    
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPageable(new PDFPageable(document));
        job.setPrintService(myPrintService);
        job.print();
    
    }
    
    private static PrintService findPrintService(String printerName) {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : printServices) {
            if (printService.getName().trim().equals(printerName)) {
                return printService;
            }
        }
        return null;
    }
    

提交回复
热议问题