PDFBox在Print()命令中冻结

时间:2015-07-21 04:01:24

标签: java pdf printing pdfbox

我尝试使用PDFBox打印现有的PDF文件。这是代码:

public void sendToPrinter(){
    File PDFFile = new File("Example.pdf");

    try {
        PDDocument pd = PDDocument.load(PDFFile);
        pd.print();
        pd.close();
    } catch (IOException | PrinterException ex) {
        System.out.println("Error: Couldn't find pdf or printers");
    }
}

然而,当我运行它时,程序会冻结pd.print()。不会抛出任何异常,也不会出现打印对话框。它没有做任何事情。以前有人有过这个问题吗?

规格:Mac OS X Yosemite,PDFBox v1.8.9,JDK1.8.0_05,HP Photosmart打印机

1 个答案:

答案 0 :(得分:1)

对于有同样问题的人。当我将所有PDF工作放到另一个线程上时,我的print()命令有效。供参考:

public void sendToPrinter() {

        //Create new Task
        Task task = new Task<Boolean>() {
            @Override
            public Boolean call() {

                //Reference the PDF file
                File PDFFile = new File("File.pdf");

                try {
                    //Load PDF & create a Printer Job
                    PDDocument pd = PDDocument.load(PDFFile);
                    PrinterJob job = PrinterJob.getPrinterJob();
                    job.setPageable(new PDFPageable(pd));

                    //Show native print dialog & wait for user to hit "print"
                    if (job.printDialog()) {
                        job.print();
                    }

                    pd.close();
                } catch (IOException | PrinterException ex) {
                }

                return true;
            }
        };
        //Run task on new thread
        new Thread(task).start();

}