您的位置:首页 > 编程语言 > Java开发

JAVA 本地打印 DocFlavor、DocPrintJob job、PrintService

2016-06-24 16:50 591 查看
//=====================调用本地打印  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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: