我在各种主机和打印机上打印包含一些标签的PDF时遇到问题。在某些主机上,我的应用程序打印了许多空白页,但在其他主机上,一切正常。我不知道为什么。我没有任何空异常或其他任何东西。
问题可能出在哪里?是不稳定的JRE还是我的代码错误?
代码:
public static String printPdf(byte[] pdf){
log.debug("printPdf(byte["+pdf.length+"])");
log.info("All printers:"+ Printer.getAllPrinters());
PrinterJob printerJob = PrinterJob.createPrinterJob();
if(printerJob==null){
log.warn("No priters were found in system");
return "[E:2]";
}
Printer printer = null;
if(printerJob.showPrintDialog(null))
{
log.info("Selected printer " + printerJob.getPrinter().getName());
printer = printerJob.getPrinter();
}
DocFlavor docType = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, aset);
String pserv = Arrays.stream(pservices).map(printService -> printService.getName()).collect(Collectors.joining(", "));
log.debug("Available print services:" + pserv);
DocPrintJob docPrintJob = null;
for(PrintService ps : pservices){
log.debug("PrintSevice: "+ps.getName());
if(ps.getName()==printer.getName()){
log.info("Serviece for a printer was founded");
docPrintJob = ps.createPrintJob();
}
}
if (docPrintJob!=null) {
log.debug("Created DocPrintJob: " +docPrintJob.getAttributes().toString());
try {
Doc doc = new SimpleDoc(new ByteArrayInputStream(pdf), docType, null);
log.info("Printing document");
docPrintJob.print(doc, aset);
} catch (PrintException e) {
log.error("PrintException", e.getMessage(), e);
return "[E:3]";
}
}else {
log.error("Null DocPrintJob");
return "[E:4]";
}
return "OK";
}