首页 > 解决方案 > Print to printer via Bluetooth(non Airprint) in iOS?

问题描述

I need to print an image from my iOS app to bluetooth thermal printer which is not AirPrint enabled. As we can not use UIKit print for non AirPrint printer, I chose to use 3rd party SDK.

Used this SDK and tried to print image where i can print small sized images, but when it comes to large one, it got crash on appending bytes saying index out of range, this is the function

`private func eachLinePixToCmd(src: [UInt8], nWidth: Int, nHeight: Int, nMode: Int) -> [UInt8] { var data = [UInt8]

    let p0 = [0, 0x80]
    let p1 = [0, 0x40]
    let p2 = [0, 0x20]
    let p3 = [0, 0x10]
    let p4 = [0, 0x08]
    let p5 = [0, 0x04]
    let p6 = [0, 0x02]
    
    let nBytesPerLine: Int = (nWidth + 7) / 8
    var k: Int = 0
    
    for _ in 0..<nHeight {
        data.append(ESC_POSCommand.beginPrintImage(xl: UInt8(nBytesPerLine % 0xff), xH: UInt8(nBytesPerLine / 0xff), yl: UInt8(1), yH: UInt8(0)).rawValue)
        var bytes = [UInt8]()
        for _ in 0..<nBytesPerLine {
            bytes.append(UInt8(p0[Int(src[k])] + p1[Int(src[k + 1])] + p2[Int(src[k + 2])] + p3[Int(src[k + 3])] + p4[Int(src[k + 4])] + p5[Int(src[k + 5])] + p6[Int(src[k + 6])] + Int(src[k + 7])))
            k = k + 8
        }
        data.append(bytes)
    }
    let rdata: [UInt8] = data.flatMap { $0 }
    return rdata
}

}`

Please let me know if any other SDK available or where to make changes on appending bytes?

Hope for the reply!!

标签: iosswiftprintersthermal-printerios-bluetooth

解决方案


我在打印图像时遇到了同样的问题,这是由于热敏打印机的限制。在这里,我在将图像发送到打印图像之前对其进行了压缩。

func resizeWithWidth(width: CGFloat) - > UIImage ? {
  let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width / size.width * size.height)))))
  imageView.contentMode = .scaleAspectFit
  imageView.image = self
  UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
  guard
  let context = UIGraphicsGetCurrentContext()
  else {
    return nil
  }
  imageView.layer.render( in: context)
  guard
  let result = UIGraphicsGetImageFromCurrentImageContext()
  else {
    return nil
  }
  UIGraphicsEndImageContext()
  return result
}

//Set the width to 256 for example

let myImage = image.resizeWithWidth(width: 256) !
  let compressData = myImage.jpegData(compressionQuality: 0.6)
//max value is 1.0 and minimum is 0.0
let compressedImage = UIImage(data: compressData!)

var ticImage = Ticket(.image(image, attributes: .alignment(.center)))

if bluetoothPrinterManager.canPrint {
  bluetoothPrinterManager.print(ticImage)
}

推荐阅读