我只想在用户不选择打印机的情况下打印 JasperReport。我搜索了它,但没有有效的解决方案。这是我的代码的相关部分:
//compile to .jasper
String report = JasperCompileManager.compileReportToFile(sourceFileName);
//fill the report
JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameter, dataSource);
//print the report
JasperPrintManager.printReport(jasperPrint, true);
我想选择一台打印机,而不是简单的 printReport。有什么办法吗?
最佳答案
它应该是这样的:
try {
String report = JasperCompileManager.compileReportToFile(sourceFileName);
JasperPrint jasperPrint = JasperFillManager.fillReport(report, para, ds);
PrinterJob printerJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
printerJob.defaultPage(pageFormat);
int selectedService = 0;
AttributeSet attributeSet = new HashPrintServiceAttributeSet(new PrinterName(printerNameShort, null));
PrintService[] printService = PrintServiceLookup.lookupPrintServices(null, attributeSet);
try {
printerJob.setPrintService(printService[selectedService]);
} catch (Exception e) {
System.out.println(e);
}
JRPrintServiceExporter exporter;
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.NA_LETTER);
printRequestAttributeSet.add(new Copies(1));
// these are deprecated
exporter = new JRPrintServiceExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, printService[selectedService]);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, printService[selectedService].getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
exporter.exportReport();
} catch (JRException e) {
e.printStackTrace();
}
关于java - 如何在指定的打印机上打印Jasper Reports?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028896/