package escpos import ( "fmt" "strings" ) // QRCorrection is the QR code error correction level. Higher levels survive // more damage at the cost of a denser code. type QRCorrection byte // QRCorrection values for GS ( k function 169. const ( QRCorrectionL QRCorrection = 48 // about 7% recovery QRCorrectionM QRCorrection = 49 // about 15% recovery QRCorrectionQ QRCorrection = 50 // about 25% recovery QRCorrectionH QRCorrection = 51 // about 30% recovery ) // QR code limits. const ( MaxQRData = 7089 // bytes the printer's symbol storage accepts MinQRModuleSize = 1 MaxQRModuleSize = 16 ) // ParseQRCorrection returns the correction level named by name: L, M, Q or H. func ParseQRCorrection(name string) (QRCorrection, error) { switch strings.ToUpper(strings.TrimSpace(name)) { case "L": return QRCorrectionL, nil case "M": return QRCorrectionM, nil case "Q": return QRCorrectionQ, nil case "H": return QRCorrectionH, nil } return 0, fmt.Errorf("%w: unknown QR correction level %q (want L, M, Q or H)", ErrInvalidArgument, name) } // QRCode appends a model 2 QR code holding data, printed with square modules // moduleSize dots wide. func (b *Builder) QRCode(data []byte, moduleSize int, level QRCorrection) error { switch { case len(data) == 0: return fmt.Errorf("%w: QR data is empty", ErrInvalidArgument) case len(data) > MaxQRData: return fmt.Errorf("%w: QR data is %d bytes, limit is %d", ErrInvalidArgument, len(data), MaxQRData) case moduleSize < MinQRModuleSize || moduleSize > MaxQRModuleSize: return fmt.Errorf("%w: QR module size %d must be within %d-%d", ErrInvalidArgument, moduleSize, MinQRModuleSize, MaxQRModuleSize) case level < QRCorrectionL || level > QRCorrectionH: return fmt.Errorf("%w: unknown QR correction level %d", ErrInvalidArgument, byte(level)) } // Function 165: select model 2. b.buf.Write([]byte{gs, '(', 'k', 4, 0, '1', 'A', '2', 0}) // Function 167: module size. b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'C', byte(moduleSize)}) // Function 169: error correction level. b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'E', byte(level)}) // Function 180: store data. The length covers cn, fn, m and the data. n := len(data) + 3 b.buf.Write([]byte{gs, '(', 'k', byte(n), byte(n >> 8), '1', 'P', '0'}) b.buf.Write(data) // Function 181: print the stored symbol. b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'Q', '0'}) return nil }