Java连接打印机打印二维码
生活随笔
收集整理的這篇文章主要介紹了
Java连接打印机打印二维码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先導入依賴
implementation 'com.google.zxing:core:3.5.1' implementation 'com.google.zxing:javase:3.5.1'?1、創建 生成二維碼和打印機的工具類
package com.tld.util;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; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;import javax.imageio.ImageIO; import javax.print.*; import javax.print.attribute.DocAttributeSet; import javax.print.attribute.HashDocAttributeSet; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.MediaSizeName; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.print.PrinterJob; import java.io.*; import java.util.Hashtable;/*** 二維碼圖片打印機工具類*/ 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;}/*** 打印保存的圖片/二維碼* @param file* @return*/public static void getPrint(File file ){try {PrintService printService = PrintServiceLookup.lookupDefaultPrintService();if (file != null) {//創建打印任務DocPrintJob jon = printService.createPrintJob();// 設置紙張大小,也可以新建MediaSize類來自定義大小// 文件類型圖片格式DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();pras.add(MediaSizeName.ISO_A4);DocAttributeSet das = new HashDocAttributeSet();InputStream input = new FileInputStream(file);//得到要打印屬性的文件類型Doc doc = new SimpleDoc(input, flavor, das);//獲取所有打印機javax.print.PrintService[] printServices = PrinterJob.lookupPrintServices();for (int i = 0; i < printServices.length; i++) {String sps = printServices[i].toString();System.out.println("打印機名稱"+sps);}//打印jon.print(doc, pras);}} catch (PrintException | FileNotFoundException e) {e.printStackTrace();}}}2、創建實體類
package com.tld.controller;import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.tld.util.MyQRUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;/*** 打印二維碼*/ @RestController @RequestMapping("/Printer") public class WebPrintController {private static final Log logger = LogFactory.getLog(MyQRUtils.class);/*** 二維碼預覽頁面* @param model* @return*/@PostMapping("/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*/@PostMapping("/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*/@PostMapping("/showEWMImage.do")public void showImageByType(HttpServletRequest request, HttpServletResponse response){String id = request.getParameter("showID"); //ID//此處可從數據庫中獲取內容String content ="打印二維碼\n打印測試\nID:"+id;//content 二維碼中的信息OutputStream outStream = null;try {outStream = response.getOutputStream();String format = "jpg";String type = "png" ;String bottomText = "一路不停"; //水印文字//生成二維碼前的配置信息BitMatrix bitMatrix = MyQRUtils.setBitMatrix(content, 180 , 180);//暫時不使用LOGO圖片//以流的形式展示MyQRUtils.megerToFile(bitMatrix, format, outStream, null,bottomText);//定義路徑,用絕對路徑Path file = new File("D:\\workspace/code.png").toPath();System.out.println("---路徑---"+file.toFile());//生成路徑并且保存文件MatrixToImageWriter.writeToPath(bitMatrix,type,file);//開始打印MyQRUtils.getPrint(file.toFile());} catch (Exception e) {logger.error("二維碼生成失敗", e);}finally{try {if(outStream!=null){outStream.flush();outStream.close();}} catch (IOException e) {logger.error("關閉數據流失敗", e);}}}}?
?
總結
以上是生活随笔為你收集整理的Java连接打印机打印二维码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lga2066服务器准系统,LGA206
- 下一篇: 无座火车票为什么不能半价?