使用 Java PDFBox 2.0.21 的 PDF 卡在“打印”状态

问题描述

我正在尝试在 Java 中设置一个打印机类,该类可以使用 PDFBox 打印 PDF 文件。 我的 printPdf 方法成功地将 .pdf 文件添加到打印机的队列中,但它根本不打印(它卡在“正在打印...”状态)。

它只发生在某些特定的 PDF 文件中。对于某些 pdf 文件,它可以完美运行,但对于某些文件,会发生问题。

这是我用来打印pdf文件的代码:

File file = new File("C:/Users/user/Desktop/Java Printing.pdf");
FilePrinter.printPdf(file,"Printer name");

FilePrinter.printPdf 方法:

public static void printPdf(File pdfFile,String laserName)
{
    PDDocument document = null;
    try {
        PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
        attr.add(MediaSizeName.ISO_A4);
        attr.add(Sides.DUPLEX);
        document = PDDocument.load(pdfFile);

        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null,null);
        PrintService myPrintService = PrintServiceLookup.lookupDefaultPrintService();

        for (PrintService printer : printServices) {
            if (printer.getName().equals(laserName))
                myPrintService = printer;
        }

        PrinterJob job = PrinterJob.getPrinterJob();

        job.setPageable(new PDFPageable(document));
        job.setPrintService(myPrintService);

        job.print(attr);

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally{
        if(document != null) {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

我尝试打印的 pdf 文件有 2 页(它没有损坏,我可以在任何网络浏览器中打开它),但在打印机队列中的文件属性中,它显示文件大小为 0 且为 0页面(参见下一张图片)

File properties inside the printer's queue

Printer's queue status when I try to print the PDF

这个问题是否与 PDFBox 有关?到我的打印机?如果我尝试从我的网络浏览器打印它,它就像一个魅力,但我真的无法用 java 打印它。

解决方法

在完全卸载并重新安装打印机驱动程序后已修复。当 Windows 告诉我它们是最新的时,它是错误的!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...