Java生成二维码并调用打印机打印
本次做订餐系统中,需要用到在Java生成二维码,并在jsp页面打印并输出,其中在action中生成二维码.
关键代码如下
1 public void reWeiMa() throws Exception{ 2 //设置页面不缓存 3 HttpServletResponse response = ServletActionContext.getResponse(); 4 HttpServletRequest quest = ServletActionContext.getRequest(); 5 Domain domain=domainService.getIp(); 6 if(domain!=null){ 7 String IP =domain.getIp(); 8 response.setHeader("Pragma","No-cache"); 9 response.setHeader("Cache-Control","no-cache"); 10 response.setDateHeader("Expires", 0); 11 12 BufferedImage image=null; 13 ServletOutputStream stream = null; 14 //二维码的图片格式 15 String format = "gif"; 16 String path= quest.getScheme() + "://"+IP+ ":" + quest.getServerPort()+ quest.getContextPath() + "/"; 17 String content=path+"OrderDetail_getMenuMaterial?menuId="+menuId; 18 int width2 = 200; 19 int height2 = 200; 20 21 Hashtable hints = new Hashtable(); 22 //内容所使用编码 23 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 24 25 try{ 26 BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width2, height2, hints); 27 int width = bitMatrix.getWidth(); 28 int height = bitMatrix.getHeight(); 29 image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 30 for (int x = 0; x < width; x++) { 31 for (int y = 0; y < height; y++) { 32 image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); //二维码图片为黑白两色 33 } 34 } 35 //ImageIO.write(image,"gif",response.getOutputStream()); 36 }catch (Exception e) { 37 // TODO: handle exception 38 } 39 //只有用这种解码方式才不出现乱码 40 String s="attachment;filename="+new String("No"+menuId+".gif"); 41 response.addHeader("Content-Disposition",s); 42 OutputStream os=new BufferedOutputStream(response.getOutputStream()); 43 response.setContentType("image/gif"); 44 ImageIO.write(image,format,os); 45 os.flush(); 46 os.close(); 47 }else{ 48 String messige="未添加域名,暂无法打印二维码"; 49 request.put("messige", messige); 50 } 51 }
jsp页面代调用生成二维码方法后,返回到打印二维码jsp中,代码如下
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="ISO-8859-1"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <div style="text-align:center;"> 11 <img alt="" src="${rootPath}/OrderDetail_reWeiMa?menuId=${menuId}"> 12 </div> 13 14 <script type="text/javascript"> 15 window.onload = function(){ 16 window.print() 17 window.close()//打印后返回到原界面 18 } 19 20 </script> 21 </body> 22 </html>
在这里的思路是在action生成的的二维码放入src标签中,直接打印整个jsp,在这个过程中,遇到了一个问题,原本调用Java内部print方法来打印二维码,但在这个过程中遇到系统无法找到指定路径,(二维码生成在服务器上,浏览器调用服务器内容),最后使用简便方法,直接打印整个jsp页面.