java实现二维码生成及调用打印机打印

来源:互联网 发布:淘宝家具店网页模板 编辑:程序博客网 时间:2024/06/06 00:53
在开发二维码打印的过程中走过几次弯路,所以在这里特意将其记录下来留作备忘。一开始参考其他博主写的文章,有介绍通过编写JAVA后台代码来获取本地默认打印机的驱动实现打印。BUT!这样就导致在本地开发测试时看似一切正常,一旦项目部署到linux环境下,就会完全失效了(JAVA后台代码去获取linux本地的打印机驱动)。还有介绍并提供编写的插件的(不甚了解这块),鉴于时间要求比较苛刻,那就简单的来吧。

需求:生成带水印效果的二维码图片,可以批量预览,并连接打印机批量打印。

开发思路:
1.编写二维码生成工具类,实现二维码图片的生成
2.提供二维码打印前的预览
3.通过隐藏的iframe实现打印(简单粗暴)

以下是自己编写的一个小案例,可以直接运行测试,并提供了code下载。如果有其它更好的实现方式,也希望大家多提出宝贵的意见。
一、项目结构

二、主要CODE
1.MyQRUtils.java 二维码工具类
package com.webprint.qr.tools;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.util.Hashtable;import javax.imageio.ImageIO;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.WriterException;import com.google.zxing.common.BitMatrix;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class MyQRUtils{private static final Log logger = LogFactory.getLog(MyQRUtils.class);private static final int BLACK = 0xFF000000;      private static final int WHITE = 0xFFFFFFFF;     private static final int LogoPart = 4;         /**     * 生成二维码前的配置信息     * @param content 生成二维码图片内容     * @param width   二维码图片的宽度     * @param height  二维码图片的高度     * @return     */    public static BitMatrix setBitMatrix(String content,int width,int height){        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();           hints.put(EncodeHintType.CHARACTER_SET, "utf-8");            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  //指定纠错等级          BitMatrix bitMatrix=null;try {bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);} catch (WriterException e) {logger.error("生成二维码错误",e);}          return bitMatrix;    }        /**     * 将LOGO图片放在二维码中间(水印效果)     * 将生成的图片以流的形式输出到页面展示     * @param matrix          BitMatrix     * @param format          图片格式     * @param outStream       输出流     * @param logoPath        LOGO地址     * @param showBottomText  二维码图片底部需要显示的问题     * @throws IOException         */    public static void megerToFile(BitMatrix matrix,String format,OutputStream outStream,String logoPath,String showBottomText) throws IOException {          BufferedImage image = toBufferedImage(matrix);          Graphics2D gs = image.createGraphics();                  //1.加入LOGO水印效果        if(null != logoPath && !"".equals(logoPath)){        //1.1 载入LOGO图片             BufferedImage logoImg = ImageIO.read(new File(logoPath));              //1.2 考虑到LOGO图片贴到二维码中,建议大小不要超过二维码的1/5;              int width = image.getWidth() / LogoPart;              int height = image.getHeight() / LogoPart;              //1.3 LOGO居中显示              int x = (image.getWidth() - width) / 2;              int y = (image.getHeight() - height) / 2;              gs.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null);              logoImg.flush();          }        //2.二维码图片底部插入文字        if(null != showBottomText && !"".equals(showBottomText)){        //2.1 设置字体样式        Font font = new Font("微软雅黑", Font.PLAIN, 14);        gs.setColor(Color.BLACK);        gs.setFont(font);        //2.2 字体显示位置        int x = (image.getWidth() - getWatermarkLength(showBottomText, gs))/2;        int y = image.getHeight()-2;        gs.drawString(showBottomText, x, y);        }        gs.dispose();          ImageIO.write(image, format, outStream);    }         /**     * 将LOGO图片放在二维码中间(水印效果)     * 将生成的图片生成到本地硬盘路径下     * @param matrix          BitMatrix     * @param format          图片格式     * @param imagePath       图片存放路径     * @param logoPath        LOGO地址     * @param showBottomText  二维码图片底部需要显示的问题     * @throws IOException         */    public static void megerToFile2(BitMatrix matrix,String format,String imagePath,String logoPath,String showBottomText) throws IOException {          BufferedImage image = toBufferedImage(matrix);          Graphics2D gs = image.createGraphics();                  //1.加入LOGO水印效果        if(null != logoPath && !"".equals(logoPath)){        BufferedImage logoImg = ImageIO.read(new File(logoPath));              int width = image.getWidth() / LogoPart;              int height = image.getHeight() / LogoPart;              int x = (image.getWidth() - width) / 2;              int y = (image.getHeight() - height) / 2;              gs.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null);              logoImg.flush();          }                //2.二维码图片底部插入文字        if(null != showBottomText && !"".equals(showBottomText)){        //2.1 设置字体样式        Font font = new Font("微软雅黑", Font.PLAIN, 14);        gs.setColor(Color.BLACK);        gs.setFont(font);        //2.2 字体显示位置        int x = (image.getWidth() - getWatermarkLength(showBottomText, gs))/2;        int y = image.getHeight()-2;        gs.drawString(showBottomText, x, y);        }        gs.dispose();        ImageIO.write(image, format, new File(imagePath));    }         /**     * 获取水印字体的长度     * @param fontString     * @param gs     * @return     */    public static int getWatermarkLength(String fontString,Graphics2D gs){    return gs.getFontMetrics(gs.getFont()).charsWidth(fontString.toCharArray(),0,fontString.length());    }        public static BufferedImage toBufferedImage(BitMatrix matrix){          int width = matrix.getWidth();          int height = matrix.getHeight();          BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);                    for(int x=0;x<width;x++){              for(int y=0;y<height;y++){                  image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);              }          }          return image;         } }

说明:二维码实现方式有多种,此处代码可根据具体需求具体开发。

2.WebPrintController.java SpringMVC的controller层代码
package com.webprint.qr.controller;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.google.zxing.common.BitMatrix;import com.webprint.qr.tools.MyQRUtils;@Controller("WebPrintController")@RequestMapping("/qrPrint")public class WebPrintController {private static final Log logger = LogFactory.getLog(MyQRUtils.class);/** * 二维码预览页面 * @param model * @return */@RequestMapping("/showList.do")public  String  showQRList(Model model){//模拟获取数据库数据List listData = new ArrayList();StringBuffer ids = new StringBuffer();String code = "print00";for (int i = 0; i < 3; i++) {Map<String,String> map = new HashMap<String,String>(); //模拟VOmap.put("id",code+""+i);ids.append(code+""+i).append(",");listData.add(map);}model.addAttribute("showListData", listData);model.addAttribute("ids", ids);return "showQR";}/** * 二维码打印页面 * 隐藏在iframe中 * @param model * @return */@RequestMapping("/printEWM.do")public  String  printQRFrame(Model model,HttpServletRequest request){String ids = request.getParameter("ids");model.addAttribute("ids", ids);return "printFrameQR";}/** * 显示二维码图片 * @param request * @param response * @throws Exception */@RequestMapping("/showEWMImage.do")public void showImageByType(HttpServletRequest request,HttpServletResponse response){String id = request.getParameter("showID"); //ID//此处可从数据库中获取内容String content ="打印二维码\n打印测试\nID:"+id;OutputStream outStream = null;try {outStream = response.getOutputStream();String format = "jpg";String bottomText = "一路不停"; //水印文字BitMatrix bitMatrix = MyQRUtils.setBitMatrix(content, 180 , 180);//暂时不使用LOGO图片MyQRUtils.megerToFile(bitMatrix, format, outStream, null,bottomText);} catch (Exception e) {logger.error("二维码生成失败", e);}finally{try {if(outStream!=null){outStream.flush();outStream.close();}} catch (IOException e) {logger.error("关闭数据流失败", e);}}}}

说明:二维码图片的展示及其打印以流的方式操作,这样就无需将图片保存在服务器上了。

3.index.jsp 首页
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <%@include file="/include.jsp" %><title></title>  </head>  <iframe id="iframePrintEWM" frameborder="0" width="0" height="0"></iframe>  <body>    <div> 1.二维码预览</br>     2.二维码打印   </div></br> </br></br><hr></br><input type="button" id ="showQRList" name="showQRList" value="二维码预览" onclick="showQRList()"/><div id='divDialog'></div><div id='divPrintDialog'></div>  </body>  <script type="text/javascript">    var height = $("body").height();    var width = $("body").width();      //二维码预览  function showQRList(){  var url ="${rootPath}/qrPrint/showList.do";  $("#divDialog").dialog({  title:"预览",  width:260,  height:500,  top:(height-500)/2,  left:(width-260)/2,  href:url,  cache:false,  closed:false,  modal:true  });  }    //二维码打印  function printEWM(ids){    $('#divDialog').window('close');    var url = '${rootPath}/qrPrint/printEWM.do?ids='+ids;  $('#iframePrintEWM').attr("src", url);  }  </script></html>

说明:将iframe放在body标签外,并将其宽高和border都设置为0,达到隐藏的效果。

4.showQR.jsp 二维码预览页
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html>  <head>  <%@include file="/include.jsp" %>    <title>showQRList</title>  </head>  <body>  <div ><div align="left" ><a href="javascript:printEWM('${ids }');" class="easyui-linkbutton" iconCls="icon-printer" style="width: 95px">二维码打印</a></div></div><div><c:forEach var="printID" items="${showListData}" varStatus="lis"> <table align="center" class="codetable"  cellpadding="0" style="float: left;border:1px solid #333333;"><tr><td align="center"><div id="bcTarget${lis.index }"><img src="${rootPath}/qrPrint/showEWMImage.do?showID=${printID.id}"></div></td></tr></table></c:forEach></div></body></html>

说明:如果项目中不需要自定义预览,此处代码可以去掉。


5.printFrameQR.jsp 隐藏的iframe页,用于打印(非常简单,非常强大)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html>  <head>  <%@include file="/include.jsp" %>    <title>printFrameQR</title>  </head>  <body onload="this.focus();this.print()"><div><c:forEach var="printID" items="${ids}" varStatus="lis"> <div id="bcTarget${lis.index }"><img src="${rootPath}/qrPrint/showEWMImage.do?showID=${printID}"></div></br></c:forEach></div></body></html>

说明:简单粗暴的方式,打印的关键就在于body标签中的 onload="this.focus();this.print()"

三、预览效果 


注意对IE打印页面的设置;

四、code下载部署说明

以上是周末自己编写的小案例,供大家参考。
环境:myeclipse8.5 + tomcat6 + jdk7 +jQuery EasyUI + core-3.3.0.jar(google zxing)

地址:http://download.csdn.net/detail/onepersontz/9794722















1 0