血翼残飞

导航

二维码以流的形式输出到界面,并打印不保存到本地

样式:

  1 package com.gdzy.ZKZHFWPT.util;
  2  
  3 import java.awt.Color;
  4 import java.awt.Font;
  5 import java.awt.Graphics2D;
  6 import java.awt.image.BufferedImage;
  7 import java.io.File;
  8 import java.io.IOException;
  9 import java.io.OutputStream;
 10 import java.util.Hashtable;
 11 
 12 import javax.imageio.ImageIO;
 13 
 14 import com.google.zxing.EncodeHintType;
 15 import org.apache.commons.logging.Log;
 16 import org.apache.commons.logging.LogFactory;
 17  
 18 import com.google.zxing.BarcodeFormat;
 19 import com.google.zxing.MultiFormatWriter;
 20 import com.google.zxing.WriterException;
 21 import com.google.zxing.common.BitMatrix;
 22 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 23  
 24 public class QRCodeUtils{
 25     
 26     private static final Log logger = LogFactory.getLog(QRCodeUtils.class);
 27     
 28     private static final int BLACK = 0xFF000000;  
 29     private static final int WHITE = 0xFFFFFFFF; 
 30     private static final int LogoPart = 4;
 31     private static int margin = 4;               //白边大小,取值范围0~4
 32     /**
 33      * 生成二维码前的配置信息
 34      * @param content 生成二维码图片内容
 35      * @param width   二维码图片的宽度
 36      * @param height  二维码图片的高度
 37      * @return
 38      */
 39     public static BitMatrix setBitMatrix(String content,int width,int height){
 40         Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
 41         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    
 42         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  //指定纠错等级
 43         hints.put(EncodeHintType.MARGIN, 4);
 44         BitMatrix bitMatrix=null;
 45         try {
 46             bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
 47         } catch (WriterException e) {
 48             logger.error("生成二维码错误",e);
 49         }
 50         return bitMatrix;
 51     }
 52     
 53     /**
 54      * 将LOGO图片放在二维码中间(水印效果)
 55      * 将生成的图片以流的形式输出到页面展示
 56      * @param matrix          BitMatrix
 57      * @param format          图片格式
 58      * @param outStream       输出流
 59      * @param logoPath        LOGO地址
 60      * @param showBottomText  二维码图片底部需要显示的问题
 61      * @throws IOException    
 62      */
 63     public static void megerToFile(BitMatrix matrix,String format,OutputStream outStream,String logoPath,String showBottomText) throws IOException {
 64         BufferedImage codeImage = toBufferedImage(matrix);
 65         Graphics2D gs = codeImage.createGraphics();
 66         //1.加入LOGO水印效果
 67         if(null != logoPath && !"".equals(logoPath)){
 68             //1.1 载入LOGO图片
 69             BufferedImage logoImg = ImageIO.read(new File(logoPath));
 70             //1.2 考虑到LOGO图片贴到二维码中,建议大小不要超过二维码的1/5;
 71             int width = codeImage.getWidth() / LogoPart;
 72             int height = codeImage.getHeight() / LogoPart;
 73             //1.3 LOGO居中显示
 74             int x = (codeImage.getWidth() - width) / 2;
 75             int y = (codeImage.getHeight() - height) / 2;
 76             gs.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null);
 77             logoImg.flush();
 78         }
 79         //画底部画布放置二维码及底部文字
 80         int backAmageW = matrix.getWidth();
 81         int backAmageH = matrix.getHeight()+50;
 82         BufferedImage backAmage = new BufferedImage(backAmageW, backAmageH, BufferedImage.TYPE_3BYTE_BGR);
 83         for(int x=0;x<backAmageW;x++){
 84             for(int y=0;y<backAmageH;y++){
 85                 backAmage.setRGB(x, y, WHITE);
 86             }
 87         }
 88         Graphics2D backgs = backAmage.createGraphics();
 89         backgs.drawImage(codeImage, 0, 0, codeImage.getWidth(), codeImage.getHeight(), null);
 90         gs.dispose();
 91         codeImage.flush();
 92         //2.二维码图片底部插入文字
 93         if(null != showBottomText && !"".equals(showBottomText)){
 94             //2.1 设置字体样式
 95             Font font = new Font("微软雅黑", Font.PLAIN, 16);
 96             backgs.setColor(Color.black);
 97             backgs.setFont(font);
 98             //2.2 字体显示位置
 99             int x = (backAmage.getWidth() - getWatermarkLength(showBottomText, gs))/2-10;
100             int y = backAmage.getHeight()-30;
101             backgs.drawString(showBottomText, x, y);
102         }
103         backgs.dispose();
104         backAmage.flush();
105         ImageIO.write(backAmage, format, outStream);
106     } 
107     
108     /**
109      * 将LOGO图片放在二维码中间(水印效果)
110      * 将生成的图片生成到本地硬盘路径下
111      * @param matrix          BitMatrix
112      * @param format          图片格式
113      * @param imagePath       图片存放路径
114      * @param logoPath        LOGO地址
115      * @param showBottomText  二维码图片底部需要显示的问题
116      * @throws IOException    
117      */
118     public static void megerToFile2(BitMatrix matrix,String format,String imagePath,String logoPath,String showBottomText) throws IOException {  
119         BufferedImage image = toBufferedImage(matrix);  
120         Graphics2D gs = image.createGraphics();  
121         
122         //1.加入LOGO水印效果
123         if(null != logoPath && !"".equals(logoPath)){
124             BufferedImage logoImg = ImageIO.read(new File(logoPath));  
125             int width = image.getWidth() / LogoPart;  
126             int height = image.getHeight() / LogoPart;  
127             int x = (image.getWidth() - width) / 2;  
128             int y = (image.getHeight() - height) / 2;  
129             gs.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null);  
130             logoImg.flush();  
131         }
132             
133         //2.二维码图片底部插入文字
134         if(null != showBottomText && !"".equals(showBottomText)){
135             //2.1 设置字体样式
136             Font font = new Font("微软雅黑", Font.PLAIN, 14);
137             gs.setColor(Color.BLACK);
138             gs.setFont(font);
139             //2.2 字体显示位置
140             int x = (image.getWidth() - getWatermarkLength(showBottomText, gs))/2;
141             int y = image.getHeight()-2;
142             gs.drawString(showBottomText, x, y);
143         }
144         gs.dispose();
145         ImageIO.write(image, format, new File(imagePath));
146     } 
147     
148     /**
149      * 获取水印字体的长度
150      * @param fontString
151      * @param gs
152      * @return
153      */
154     public static int getWatermarkLength(String fontString,Graphics2D gs){
155         return gs.getFontMetrics(gs.getFont()).charsWidth(fontString.toCharArray(),0,fontString.length());
156     }
157     
158     public static BufferedImage toBufferedImage(BitMatrix matrix){  
159         int width = matrix.getWidth();  
160         int height = matrix.getHeight();  
161         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);  
162           
163         for(int x=0;x<width;x++){  
164             for(int y=0;y<height;y++){  
165                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
166             }  
167         }  
168         return image;     
169     } 
170 }
二维码生成工具类
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ include file="/jsp/common/commonfile.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <!-- 与本页面直接相关的JavaScript脚本放置区域. -->
    <title>外部项目二维码显示</title>
    <script type="application/javascript">
        function closeQrCodeodal() {
            parent.$("#win").dialog('close');
        }
        function printQrCode() {
            window.location.href = "printQrCode.action";
        }
    </script>
</head>
<body style="background-color: white">
<div>
    <div style="width: 300px;height: 330px;margin: 0 auto;">
        <img src="printQrCode.action">
    </div>
    <div style="margin-left: 100px;margin-right: 80px;">
        <a href="javascript:void(0);" class="btn btn-primary" style="width:100px;height: 25px; margin-left: 40px;"
           onclick="closeQrCodeodal();">返回</a>
        <a href="javascript:void(0);" class="btn btn-primary" style="width:100px;height: 25px; float: right; margin-right: 40px;"
           onclick="printQrCode()">打印</a>
    </div>
    <div style="background-color: white;height: 30px;"></div>
</div>
</body>
</html>
二维码展示界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ include file="/jsp/common/commonfile.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>外部项目二维码打印</title>
    <script type="application/javascript">
        function closeQrCodeodal() {
            parent.$("#win").dialog('close');
        }
    </script>
</head>
<body onload="this.focus();this.print();closeQrCodeodal()" style="background-color: white">
<div>
    <div style="width: 330px;height: 330px;margin:0 auto;">
        <img src="showQRCode.action?extProjectId=${extProjectId}">
    </div>
    <div style="background-color: white;height: 30px;"></div>
</div>

</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ include file="/jsp/common/commonfile.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>外部项目二维码打印</title>
    <script type="application/javascript">
        function closeQrCodeodal() {
            parent.$("#win").dialog('close');
        }
    </script>
</head>
<body onload="this.focus();this.print();closeQrCodeodal()" style="background-color: white">
<div>
    <div style="width: 330px;height: 330px;margin:0 auto;">
        <img src="showQRCode.action?extProjectId=${extProjectId}">
    </div>
    <div style="background-color: white;height: 30px;"></div>
</div>

</body>
</html>
打印二维码,通过
 1  public void printQrCode() throws IOException {
 2         HttpServletResponse response = ServletActionContext.getResponse();
 3         OutputStream outputStream = null;
 4         try {
 5             outputStream = response.getOutputStream();
 6             String content = "人生若只如初见,何事秋风悲画扇";
 7             String logoPath = "E:\\1.jpg";
 8             String format = "jpg";
 9             String bottomText = "人生若只如初见,何事秋风悲画扇";
10             BitMatrix bitMatrix = QRCodeUtils.setBitMatrix(content, 250, 250);
11             QRCodeUtils.megerToFile(bitMatrix, format, outputStream, logoPath, bottomText);
12         } catch (IOException e) {
13             e.printStackTrace();
14         } finally {
15             if (outputStream != null) {
16                 try {
17                     outputStream.flush();
18                     outputStream.close();
19                 } catch (IOException e) {
20                     e.printStackTrace();
21                 }
22             }
23         }
24     }
controller

 打印通过<body>的 onload="this.focus();this.print(); 调取打印机进行打印

posted on 2019-01-21 13:35  血翼残飞  阅读(597)  评论(0编辑  收藏  举报