//=====================调用本地打印 1 打印 JasperPrint 文件
private void printPDF(JasperPrint jasperPrint){
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
HashPrintServiceAttributeSet psat = new HashPrintServiceAttributeSet();
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200, pservices,
defaultService, flavor, aset);
if(service != null){
try {
PrintServiceExporter exporter = new PrintServiceExporter();
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, aset);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, psat);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, false);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, false);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, service);
exporter.setParameter(JRPrintServiceExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRPrintServiceExporterParameter.IGNORE_PAGE_MARGINS, true);
exporter.exportReport();
} catch (Exception fe) {
logger.info("打印失败", fe);
}
}else {
logger.info("打印失败");
}
}
//=====================调用本地打印 2 根据字节数组打印
private void print(){
DocFlavor flavor=DocFlavor.INPUT_STREAM.JPEG;
//get a printer
PrintService[] printers=PrintServiceLookup.lookupPrintServices( flavor, null);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200, pservices,
defaultService, flavor, aset);
//job
DocPrintJob job=service.createPrintJob();
//document
//已输出流进行打印
BufferedImage img=new BufferedImage( 400,300, BufferedImage.TYPE_USHORT_555_RGB );
Graphics g=img.getGraphics();
g.drawString(code, 100,100);
ByteArrayOutputStream outstream=new ByteArrayOutputStream();
ImageIO.write( img, "jpg", outstream);
byte[] buf=outstream.toByteArray();
InputStream stream=new ByteArrayInputStream(buf);
Doc doc=new SimpleDoc(stream,flavor,null);
// 根据文件路径进行打印
// FileInputStream fis = new FileInputStream("D:" + File.separator + "zkyzl.txt");
// DocAttributeSet das = new HashDocAttributeSet();
// Doc doc = new SimpleDoc(fis, flavor, das);
//print
job.print(doc, null);
}JAVA 本地打印 DocFlavor、DocPrintJob job、PrintService
最新推荐文章于 2025-09-28 16:07:24 发布
本文介绍如何使用Java实现两种方式的本地打印:一种是通过JasperPrint对象直接打印JasperReports报告;另一种是从字节数组创建图像并将其转换为JPEG格式进行打印。文章详细展示了如何设置打印服务、创建打印任务及文档,并提供了完整的代码示例。
1662

被折叠的 条评论
为什么被折叠?



