使用Java PDFBox 2.0.21打印PDF时部分文件卡在打印状态无输出
Java基于PDFBox实现PDF打印的故障排查需求
核心故障表现
- 依托PDFBox开发的PDF打印工具类,
printPdf方法可将部分PDF文件成功提交至打印机队列,但部分场景下打印任务会卡在“正在打印”状态,无实际打印动作输出 - 故障仅针对特定PDF文件触发:同一套打印逻辑下,部分PDF可正常完成全流程打印,部分PDF会触发上述故障
- 触发故障的待打印PDF共2页,本身无文件损坏,可通过任意网页浏览器正常打开;从浏览器直接打印该PDF可正常输出,通过Java代码提交打印任务时,打印机队列属性页显示该任务文件大小为0、页数为0(对应故障状态可参考:打印机队列内的文件属性截图、故障状态下的打印机队列显示截图),始终无法完成实际打印
现有打印实现
方法调用示例
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触发打印任务0文件大小、0页数、卡队列状态的根本原因
- 判定该问题根源是否与PDFBox的打印实现逻辑相关,或是与本地打印机配置相关
内容的提问来源于stack exchange,提问作者Zakuraai
相关产品推荐
相关产品推荐

