zhangherong
2025-05-27 92bc6dca274eb45dc330f63b5a3f90a01458e157
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
package org.jeecg.modules.tms.utils;
 
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import java.awt.print.*;
import java.awt.image.BufferedImage;
import java.awt.*;
 
public class QrCodePrinterUtils implements Printable {
 
    private final BufferedImage image;
 
    public QrCodePrinterUtils(BufferedImage image) {
        this.image = image;
    }
 
    /**
     * 打印二维码
     */
    public void print() {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(this);
 
        // 弹出打印对话框(可选)
        if (job.printDialog()) {
            try {
                job.print();
            } catch (PrinterException e) {
                System.err.println("打印失败: " + e.getMessage());
            }
        }
    }
 
    /**
     * 实现 Printable 接口的打印方法
     */
    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
            return NO_SUCH_PAGE;
        }
 
        Graphics2D g2d = (Graphics2D) graphics;
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
 
        // 计算居中坐标
        double pageWidth = pageFormat.getImageableWidth();
        double pageHeight = pageFormat.getImageableHeight();
        double imgWidth = image.getWidth();
        double imgHeight = image.getHeight();
 
        double scale = Math.min(pageWidth / imgWidth, pageHeight / imgHeight);
        g2d.scale(scale, scale);
        g2d.drawImage(image, 0, 0, null);
 
        return PAGE_EXISTS;
    }
 
    /**
     * 使用默认打印机打印,不弹对话框
     */
    public static void noDialogPrint(){
        BufferedImage qrImage = QrCodeUtils.generateQrCode("Silent Print", 300, 300);
        QrCodePrinterUtils printer = new QrCodePrinterUtils(qrImage);
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(printer);
        try {
            job.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}