zjh
2024-06-12 5a6a1ae4f22cae6323e41d35c5f32137afddd2d0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package com.ltkj.web.controller.barcode;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
 
import java.awt.print.*;
import java.util.HashMap;
import java.util.Map;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.pdf417.PDF417Writer;
import com.ltkj.common.utils.StringUtils;
 
import static java.awt.print.Printable.PAGE_EXISTS;
 
/**
 * 生成条形码(可显示文本内容)
 *
 */
public class BarCodeUtils {
 
    /**
     * 默认图片宽度
     */
    private static final int DEFAULT_PICTURE_WIDTH = 250;
 
    /**
     * 默认图片高度
     */
    private static final int DEFAULT_PICTURE_HEIGHT = 150;
 
    /**
     * 默认条形码宽度
     */
    private static final int DEFAULT_BAR_CODE_WIDTH = 200;
 
    /**
     * 默认条形码高度
     */
    private static final int DEFAULT_BAR_CODE_HEIGHT = 70;
 
    /**
     * 默认字体大小
     */
    private static final int DEFAULT_FONT_SIZE = 15;
 
    /**
     * 设置 条形码参数
     */
    private static final Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
 
    static {
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    }
 
    /**
     * 获取条形码图片
     *
     * @param codeValue 条形码内容
     * @return 条形码图片
     */
    public static BufferedImage getBarCodeImage(String codeValue) {
        return getBarCodeImage(codeValue, DEFAULT_BAR_CODE_WIDTH, DEFAULT_BAR_CODE_HEIGHT);
    }
 
    /**
     * 获取条形码图片
     *
     * @param codeValue 条形码内容
     * @param width 宽度
     * @param height 高度
     * @return 条形码图片
     */
    public static BufferedImage getBarCodeImage(String codeValue, int width, int height) {
        // CODE_128是最常用的条形码格式
        return getBarCodeImage(codeValue, width, height, BarcodeFormat.CODE_128);
    }
 
    /**
     * 获取条形码图片
     *
     * @param codeValue 条形码内容
     * @param width 宽度
     * @param height 高度
     * @param barcodeFormat 条形码编码格式
     * @return 条形码图片
     */
    public static BufferedImage getBarCodeImage(String codeValue, int width, int height, BarcodeFormat barcodeFormat) {
        Writer writer;
        switch (barcodeFormat) {
            case CODE_128:
                // 最常见的条形码,但是不支持中文
                writer = new Code128Writer();
                break;
            case PDF_417:
                // 支持中文的条形码格式
                writer = new PDF417Writer();
                break;
            // 如果使用到其他格式,可以在这里添加
            default:
                writer = new Code128Writer();
        }
 
        // 编码内容, 编码类型, 宽度, 高度, 设置参数
        BitMatrix bitMatrix;
        try {
            bitMatrix = writer.encode(codeValue, barcodeFormat, width, height, hints);
        } catch (WriterException e) {
            throw new RuntimeException("条形码内容写入失败");
        }
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }
 
 
    /**
     * 获取条形码
     *111111
     * @param codeValue 条形码内容
     * @param bottomStr 底部文字
     * @param topLeftStr 左上角文字
     * @param topRightStr 右上角文字
     * @return
     */
    public static BufferedImage getBarCodeWithWords(String codeValue, String bottomStr, String topLeftStr,
                                                    String topRightStr) {
        return getCodeWithWords(getBarCodeImage(codeValue), bottomStr, topLeftStr, topRightStr, DEFAULT_PICTURE_WIDTH,
                DEFAULT_PICTURE_HEIGHT, 0, 0, 0, 0, 0, 0, DEFAULT_FONT_SIZE);
    }
 
    /**
     * 获取条形码
     *
     * @param codeImage 条形码图片
     * @param bottomStr 底部文字
     * @param topLeftStr 左上角文字
     * @param topRightStr 右上角文字
     * @param pictureWidth 图片宽度
     * @param pictureHeight 图片高度
     * @param codeOffsetX 条形码宽度
     * @param codeOffsetY 条形码高度
     * @param topLeftOffsetX 左上角文字X轴偏移量
     * @param topLeftOffsetY 左上角文字Y轴偏移量
     * @param topRightOffsetX 右上角文字X轴偏移量
     * @param topRightOffsetY 右上角文字Y轴偏移量
     * @param fontSize 字体大小
     * @return 条形码图片
     */
    public static BufferedImage getCodeWithWords(BufferedImage codeImage, String bottomStr, String topLeftStr,
                                                 String topRightStr, int pictureWidth, int pictureHeight, int codeOffsetX, int codeOffsetY,
                                                 int topLeftOffsetX, int topLeftOffsetY, int topRightOffsetX, int topRightOffsetY, int fontSize) {
        BufferedImage picImage = new BufferedImage(pictureWidth, pictureHeight, BufferedImage.TYPE_INT_RGB);
 
        Graphics2D g2d = picImage.createGraphics();
        // 抗锯齿
        setGraphics2D(g2d);
        // 设置白色
        setColorWhite(g2d, picImage.getWidth(), picImage.getHeight());
 
        // 条形码默认居中显示
        int codeStartX = (pictureWidth - codeImage.getWidth()) / 2 + codeOffsetX;
        int codeStartY = (pictureHeight - codeImage.getHeight()) / 2 + codeOffsetY;
        // 画条形码到新的面板
        g2d.drawImage(codeImage, codeStartX, codeStartY, codeImage.getWidth(), codeImage.getHeight(), null);
 
        // 画文字到新的面板
        g2d.setColor(Color.BLACK);
        // 字体、字型、字号
        g2d.setFont(new Font("微软雅黑", Font.PLAIN, fontSize));
        // 文字与条形码之间的间隔
        int wordAndCodeSpacing = 3;
 
        if (StringUtils.isNotEmpty(bottomStr)) {
            // 文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(bottomStr);
            // 文字X轴开始坐标,这里是居中
            int strStartX = codeStartX + (codeImage.getWidth() - strWidth) / 2;
            // 文字Y轴开始坐标
            int strStartY = codeStartY + codeImage.getHeight() + fontSize + wordAndCodeSpacing;
            // 画文字
            g2d.drawString(bottomStr, strStartX, strStartY);
        }
 
        if (StringUtils.isNotEmpty(topLeftStr)) {
            // 文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(topLeftStr);
            // 文字X轴开始坐标
            int strStartX = codeStartX + topLeftOffsetX;
            // 文字Y轴开始坐标
            int strStartY = codeStartY + topLeftOffsetY - wordAndCodeSpacing;
            // 画文字
            g2d.drawString(topLeftStr, strStartX, strStartY);
        }
 
        if (StringUtils.isNotEmpty(topRightStr)) {
            // 文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(topRightStr);
            // 文字X轴开始坐标,这里是居中
            int strStartX = codeStartX + codeImage.getWidth() - strWidth + topRightOffsetX;
            // 文字Y轴开始坐标
            int strStartY = codeStartY + topRightOffsetY - wordAndCodeSpacing;
            // 画文字
            g2d.drawString(topRightStr, strStartX, strStartY);
        }
 
        g2d.dispose();
        picImage.flush();
 
        return picImage;
    }
 
    /**
     * 设置 Graphics2D 属性 (抗锯齿)
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }
 
    /**
     * 设置背景为白色
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d, int width, int height) {
        g2d.setColor(Color.WHITE);
        // 填充整个屏幕
        g2d.fillRect(0, 0, width, height);
        // 设置笔刷
        g2d.setColor(Color.BLACK);
    }
 
 
    public static void barCodePrint(BufferedImage bufferedImage, int pageWidth, int pageHeight, int showWidth, int showHeight) {
        // 通俗理解就是书、文档
        Book book = new Book();
        // 设置成竖打
        PageFormat pf = new PageFormat();
        pf.setOrientation(PageFormat.PORTRAIT);
        // 通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。
        Paper paper = new Paper();
        //纸张大小
        paper.setSize(pageWidth, pageHeight);
        paper.setImageableArea(0, 0, pageWidth, pageHeight);
        pf.setPaper(paper);
        // 把 PageFormat 和 Printable 添加到书中,组成一个页面
        book.append((graphics, pageFormat, pageIndex) -> {
            //将图片绘制到graphics对象中(为什么把需要打印的内容drawImage就可以实现打印自己取看值传递一引用传递的区别)
            graphics.drawImage(bufferedImage, 0, 0, showWidth, showHeight, null);
            return PAGE_EXISTS;//返回0(PAGE_EXISTS)则执行打印,返回1(NO_SUCH_PAGE)则不执行打印
        }, pf);
        // 获取打印服务对象
        PrinterJob job = PrinterJob.getPrinterJob();
        // 设置打印类
        job.setPageable(book);
        try {
            //可以用printDialog显示打印对话框,在用户确认后打印;也可以直接打印
            job.printDialog();
            job.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
 
}