码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA创建二维码打印代码

时间:2019-08-11 13:26:34      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:二维码   文件流   eth   catch   对话   bar   throw   log   setfont   

jsp前端代码:

<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="printTag()">打印条码</a>

//打印
        function printTag() {
            var row = $(‘#dg‘).datagrid(‘getSelected‘);
            if (row) {
                $.messager.confirm(‘Confirm‘, ‘您确定要打印这条数据吗?‘, function (r) {
                    if (r) {
                        var prodname =encodeURI(encodeURI(row.prodname));
                        $.post(‘${pageContext.request.contextPath}/service/product/print?prodno=‘ + row.prodno +"&prodname="+prodname, {}, function (data) {
                            if (data == 1) {
                                $(‘#dg‘).datagrid(‘reload‘);    // reload the user data
                            } else {
                                $.messager.show({    // show error message
                                    title: ‘Error‘,
                                    msg: result.msg
                                });
                            }
                        }, ‘json‘);
                    }
                });
            }
            else {
                $.messager.alert(‘提示‘, ‘请选择你要打印的行!‘, ‘信息‘);
            }
        }

 

Controller代码:

//打印
  @RequestMapping(value = "/print",method=RequestMethod.POST)
  public void print(String prodno,String prodname){
   if (prodno != null && prodname != null) {
    JbarcodeUtil.createBarcode(prodno, new File("F:/标签.jpeg"),prodname);
    Print.print1();
   }
  }
 
 
 
util代码:
package com.springmvc.util;
import java.io.File;
import java.io.FileInputStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.swing.JFileChooser;
public class Print {
 public static void print1() {
  
   File file =  new File("F:/标签.jpeg"); // 获取选择的文件
   // 构建打印请求属性集
   HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
   // 设置打印格式,因为未确定类型,所以选择autosense
   DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
   // 查找所有的可用的打印服务
   PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
   // 定位默认的打印服务
   PrintService defaultService = PrintServiceLookup
     .lookupDefaultPrintService();
   // 显示打印对话框
   PrintService service = ServiceUI.printDialog(null, 100, 100, printService, defaultService, flavor, pras);
   if (service != null) {
    try {
     DocPrintJob job = service.createPrintJob(); // 创建打印作业
     FileInputStream fis = new FileInputStream(file); // 构造待打印的文件流
     DocAttributeSet das = new HashDocAttributeSet();
     Doc doc = new SimpleDoc(fis, flavor, das);
     job.print(doc, pras);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }
 
 
 
package com.springmvc.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import org.jbarcode.JBarcode;
import org.jbarcode.JBarcodeFactory;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.TextPainter;
import org.jbarcode.util.ImageUtil;
public class JbarcodeUtil {
  // 设置条形码高度
    private static final int BARCODE_HEIGHT = 20;
    // 设置条形码默认分辨率
    private static final int BARCODE_DPI = ImageUtil.DEFAULT_DPI;
    // 设置条形码字体样式
    private static final String FONT_FAMILY = "新宋体";
    // 设置条形码字体大小
    private static final int FONT_SIZE = 15;
    // 设置条形码文本
    public static String TEXT = "";
    // 创建jbarcode
    private static JBarcode jbc = null;
    // 生成条形码最下面一行;
    private static String name = "";
    static JBarcode getJBarcode() throws InvalidAtributeException {
        /**
         * 参考设置样式: barcode.setEncoder(Code128Encoder.getInstance()); //设置编码
         * barcode.setPainter(WidthCodedPainter.getInstance());// 设置Painter
         * barcode.setTextPainter(BaseLineTextPainter.getInstance()); //设置TextPainter
         * barcode.setBarHeight(17); //设置高度
         * barcode.setWideRatio(Double.valueOf(30).doubleValue());// 设置宽度比率
         * barcode.setXDimension(Double.valueOf(2).doubleValue()); // 设置尺寸,大小 密集程度
         * barcode.setShowText(true); //是否显示文本 barcode.setCheckDigit(true); //是否检查数字
         * barcode.setShowCheckDigit(false); //是否显示检查数字
         */
        if (jbc == null) {
            // 生成code128
            jbc = JBarcodeFactory.getInstance().createCode128();
            jbc.setEncoder(Code128Encoder.getInstance());
            // jbc.setTextPainter(CustomTextPainter.getInstance());
            jbc.setTextPainter(CustomTextPainter.getInstance());
            // jbc.setWideRatio(Double.valueOf(1).doubleValue());
            // jbc.setXDimension(Double.valueOf(1).doubleValue());
            jbc.setBarHeight(BARCODE_HEIGHT);
            // jbc.setXDimension(1);
            jbc.setShowText(true);
        }
        return jbc;
    }
    /**
     * @descript:生成条形码文件
     * @param message 条形码内容
     * @param file 生成文件
     */
    public static void createBarcode(String message, File file, String text) {
        try {
            FileOutputStream fos = new FileOutputStream(file);
            createBarcode(message, fos, text);
            fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * @descript:生成条形码并写入指定输出流
     * @param message 条形码内容
     * @param os 输出流
     */
    public static void createBarcode(String message, OutputStream os, String text) {
        try {
            String a = message;
            name = a;
            // 设置条形码文本
            TEXT  = URLDecoder.decode(text, "utf-8");
            // 创建条形码的BufferedImage图像
            BufferedImage image = getJBarcode().createBarcode(a);
            ImageUtil.encodeAndWrite(image, ImageUtil.JPEG, os, 10, 0);
            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 静态内部类 自定义的 TextPainter, 允许定义字体,大小,文本等 参考底层实现:BaseLineTextPainter.getInstance()
     */
    protected static class CustomTextPainter implements TextPainter {
        private static CustomTextPainter instance = new CustomTextPainter();
        public static CustomTextPainter getInstance() {
            return instance;
        }
        public void paintText(BufferedImage barCodeImage, String text, int width) {
            // 绘图
            // BufferedImage bi = barCodeImage;
            Graphics g2d = barCodeImage.getGraphics();
            // 创建字体
            Font font = new Font("防宋", Font.PLAIN, 12);
            g2d.setFont(font);
            FontMetrics fm = g2d.getFontMetrics();
            g2d.setColor(Color.WHITE); // 143 30
            g2d.fillRect(0, 0, 200, 30);
            g2d.fillRect(0, 55, 200, 111);
            // g2d.fillRect(0, 0, 200, barCodeImage.getHeight() * 1 / 20);
            // g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10),
            // barCodeImage.getWidth(), (height * 9 / 10));
            // 55 143 111
            g2d.setColor(Color.BLACK);
            String a = TEXT;
            // 绘制文本
            g2d.drawString(a, 35, 20);
            // 绘制条形码
            g2d.drawString(name, 20, 70);
        }
    }
}

JAVA创建二维码打印代码

标签:二维码   文件流   eth   catch   对话   bar   throw   log   setfont   

原文地址:https://www.cnblogs.com/jiyang54/p/11334306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!