iOS蓝牙连接打印机,打印小票

我们看看打印出来的效果 

打印小票数据处理,针对服务器返回的数据进行数据封装成model dataPrint是服务器返回的json数据

- (HLPrinter *)getPrinter{
    PrinterModel *printModel = [PrinterModel mj_objectWithKeyValues:dataPrint];

    HLPrinter *printer = [[HLPrinter alloc] init];
    [printer appendText:[NSString stringWithFormat:@"【%@】",printModel.orderTitle] alignment:HLTextAlignmentCenter];
    [printer appendText:@"- - 已支付 - -" alignment:HLTextAlignmentCenter];
    [printer appendSeperatorLine];
    
    [printer appendTitle:@"订单编号 :" value:printModel.orderNumber valueOffset:130];
    [printer appendTitle:@"下单时间 :" value:printModel.orderCreateTime valueOffset:130];
    [printer appendSeperatorLine];
    
    NSMutableString *customerName = [[NSMutableString alloc] initWithString:printModel.customerName];
    if(customerName.length >= 36){ // 客户名称
        [customerName substringToIndex:36];
        [customerName deleteCharactersInRange:NSMakeRange(36, customerName.length-36)];
        [customerName insertString:@"            " atIndex:18];
    }else if (customerName.length >= 18) {
        [customerName insertString:@"            " atIndex:18];
    }
    [printer appendTitle:@"客户名称 :" value:customerName valueOffset:130];
    [printer appendTitle:@"单据类型 :" value:printModel.orderType valueOffset:130];
    [printer appendTitle:@"销售人员 :" value:printModel.salesMan valueOffset:130];
    [printer appendTitle:@"销售部门 :" value:printModel.salesDepartment valueOffset:130];
    [printer appendTitle:@"发货仓库 :" value:printModel.warehouse valueOffset:130];
    [printer appendSeperatorLine];

    [printer appendFourLinesText:@"商品名称" middleText:@"数量" rightText:@"单位" moneyText:@"价格(元)" isTitle:YES];
    
    NSMutableArray *arrProduct = [self showProductData:printModel]; // 拼装商品信息
    for (ProductBeans *product in arrProduct) {
        [printer appendFourLinesText:product.productName middleText:product.productCount rightText:product.productUnit moneyText:product.productPrice  isTitle:NO];
    }
    [printer appendSeperatorLine];
    
    [printer appendSubtotalText:@"小计" centerText:printModel.productCount rightText:printModel.productTotalPrice isTitle:YES];
    [printer appendSeperatorLine];
    
    if (printModel.giftBeans.count > 0) { // 赠送商品大于0显示赠品
        [printer appendText:@"【赠送商品】" alignment:HLTextAlignmentCenter];
        [printer appendNewLine];
        [printer appendLeftText:@"商品名称" middleText:@"数量" rightText:@"单位" isTitle:YES];

        NSMutableArray *arrGift = [self showGiftData:printModel]; //拼装赠送商品信息
        for (GiftBeans *gift in arrGift) {
            [printer appendLeftText:gift.productName middleText:gift.productCount rightText:gift.productUnit isTitle:NO];
        }
        [printer appendSeperatorLine];
        [printer appendTitle:@"小计" value:printModel.giftCount valueOffset:500 - 62];
        [printer appendSeperatorLine];
    }
    
    CGFloat titleWidth = [printModel.totalPrice boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 18) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:11 weight:UIFontWeightRegular]} context:nil].size.width;
    [printer appendTitle:@"实付金额 :" value:printModel.totalPrice valueOffset:520 - (titleWidth)];
    [printer appendNewLine];
    [printer appendNewLine];
    [printer appendNewLine];
    [printer appendNewLine];
    
    // 你也可以利用UIWebView加载HTML小票的方式,这样可以在远程修改小票的样式和布局。
    // 注意点:需要等UIWebView加载完成后,再截取UIWebView的屏幕快照,然后利用添加图片的方法,加进printer
    // 截取屏幕快照,可以用UIWebView+UIImage中的catogery方法 - (UIImage *)imageForWebView
    
    return printer;
}

针对商品名称进行换行逻辑处理,把原数据进行组装

/// 商品名称
- (NSMutableArray *)showProductData:(PrinterModel *)printModel{
    NSMutableArray *mArray = [[NSMutableArray alloc]initWithCapacity:0];
    NSInteger  priceLength = 0;
    NSInteger  unitLength = 0;
    NSInteger  countLength = 0;
    
    for (int i=0; i<printModel.productBeans.count; i++) {
        ProductBeans *model = printModel.productBeans[i];
        if (model.productUnit.length>unitLength) {
            unitLength = model.productUnit.length;
        }
        if (model.productPrice.length>priceLength) {
            priceLength = model.productPrice.length;
        }
        if (model.productCount.length>countLength) {
            countLength = model.productCount.length;
        }
        
        NSString *name = model.productName;
        if (name.length >= 28) {
            for (int i=0; i<3; i++) { // 三行时
                ProductBeans *subModel = [[ProductBeans alloc]init];
                if (i == 0) {
                    subModel.productName = [name substringWithRange:NSMakeRange(0, 14)];
                    subModel.productCount = model.productCount;
                    subModel.productUnit = model.productUnit;
                    subModel.productPrice = model.productPrice;
                }else if (i == 1) {
                    subModel.productName = [name substringWithRange:NSMakeRange(14, 14)];
                    subModel.productCount = @"";
                    subModel.productUnit = @"";
                    subModel.productPrice = @"";
                }else {
                    if (name.length > 42) {
                        subModel.productName = [name substringWithRange:NSMakeRange(28, 14)];
                    }else{
                        subModel.productName = [name substringWithRange:NSMakeRange(28, name.length-28)];
                    }
                    subModel.productCount = @"";
                    subModel.productUnit = @"";
                    subModel.productPrice = @"";
                }
                [mArray addObject:subModel];
            }
        }else if (name.length >= 14) {
            for (int i=0; i<2; i++) { // 两行时
                ProductBeans *subModel = [[ProductBeans alloc]init];
                if (i == 0) {
                    subModel.productName = [name substringWithRange:NSMakeRange(0, 14)];
                    subModel.productCount = model.productCount;
                    subModel.productUnit = model.productUnit;
                    subModel.productPrice = model.productPrice;
                }else {
                    if (name.length > 28) {
                        subModel.productName = [name substringWithRange:NSMakeRange(14, 14)];
                    }else{
                        subModel.productName = [name substringWithRange:NSMakeRange(14, name.length-14)];
                    }
                    subModel.productCount = @"";
                    subModel.productUnit = @"";
                    subModel.productPrice = @"";
                }
                [mArray addObject:subModel];
            }
        }else {
            [mArray addObject:model];
        }
    }
    
    printModel.productBeans = mArray;
    for (int i=0; i<printModel.productBeans.count; i++) {
        ProductBeans *model = printModel.productBeans[i];
        NSMutableString *unit = [NSMutableString stringWithString:model.productUnit];
        if (unit.length < unitLength) {
            NSInteger length = unitLength - unit.length;
            for (int i=0; i<length; i++) {
                [unit insertString:@" " atIndex:0];
            }
            model.productUnit = unit;
        }
        NSMutableString *price = [NSMutableString stringWithString:model.productPrice];
        if (price.length < priceLength) {
            NSInteger length = priceLength - price.length;
            for (int i=0; i<length; i++) {
                [price insertString:@" " atIndex:0];
            }
            model.productPrice =  price;

        }
        NSMutableString *count = [NSMutableString stringWithString:model.productCount];
        if (count.length < countLength) {
            NSInteger length = countLength - count.length;
            for (int i=0; i<length; i++) {
                [count insertString:@" " atIndex:0];
            }
            model.productCount = count;
        }
    }
    return mArray;
}

针对赠送的商品进行数据组装处理

/// 赠送信息
- (NSMutableArray *)showGiftData:(PrinterModel *)printModel{
    NSMutableArray *arraygift = [[NSMutableArray alloc]initWithCapacity:0];
    NSInteger  priceLength = 0;
    NSInteger  unitLength = 0;
    NSInteger  countLength = 0;
    
    for (int i=0; i<printModel.giftBeans.count; i++) {
        GiftBeans *model = printModel.giftBeans[i];
        if (model.productUnit.length>unitLength) {
            unitLength = model.productUnit.length;
        }
        if (model.productPrice.length>priceLength) {
            priceLength = model.productPrice.length;
        }
        if (model.productCount.length>countLength) {
            countLength = model.productCount.length;
        }

        NSString *name = model.productName;
        if (name.length >= 44) {
            for (int i=0; i<3; i++) { // 三行时
                GiftBeans *subModel = [[GiftBeans alloc]init];
                if (i == 0) {
                    subModel.productName = [name substringWithRange:NSMakeRange(0, 22)];
                    subModel.productCount = model.productCount;
                    subModel.productUnit = model.productUnit;
                    subModel.productPrice = model.productPrice;
                }else if (i == 1) {
                    subModel.productName = [name substringWithRange:NSMakeRange(22, 22)];
                    subModel.productCount = @"";
                    subModel.productUnit = @"";
                    subModel.productPrice = @"";
                }else {
                    subModel.productName = [name substringWithRange:NSMakeRange(44, name.length-44)];
                    subModel.productCount = @"";
                    subModel.productUnit = @"";
                    subModel.productPrice = @"";
                }
                [arraygift addObject:subModel];
            }
        }else if (name.length >= 22) {
            for (int i=0; i<2; i++) { // 两行时
                GiftBeans *subModel = [[GiftBeans alloc]init];
                if (i == 0) {
                    subModel.productName = [name substringWithRange:NSMakeRange(0, 22)];
                    subModel.productCount = model.productCount;
                    subModel.productUnit = model.productUnit;
                    subModel.productPrice = model.productPrice;
                }else {
                    subModel.productName = [name substringWithRange:NSMakeRange(22, name.length-22)];
                    subModel.productCount = @"";
                    subModel.productUnit = @"";
                    subModel.productPrice = @"";
                }
                [arraygift addObject:subModel];
            }
        }else {
            [arraygift addObject:model];
        }
    }
    
    printModel.giftBeans = arraygift;
    for (int i=0; i<printModel.giftBeans.count; i++) {
        GiftBeans *model = printModel.giftBeans[i];
        NSMutableString *unit = [NSMutableString stringWithString:model.productUnit];
        if (unit.length < unitLength) {
            NSInteger length = unitLength - unit.length;
            for (int i=0; i<length; i++) {
                [unit insertString:@" " atIndex:0];
            }
            model.productUnit = unit;
        }
        NSMutableString *price = [NSMutableString stringWithString:model.productPrice];
        if (price.length < priceLength) {
            NSInteger length = priceLength - price.length;
            for (int i=0; i<length; i++) {
                [price insertString:@" " atIndex:0];
            }
            model.productPrice =  price;
           
        }
        NSMutableString *count = [NSMutableString stringWithString:model.productCount];
        if (count.length < countLength) {
            NSInteger length = countLength - count.length;
            for (int i=0; i<length; i++) {
                [count insertString:@" " atIndex:0];
            }
            model.productCount = count;
        }
    }
    return arraygift;
}

使用打印功能进行打印

- (void)blueButtonAction{
    
    NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey:@NO};//不弹窗(配置)
    self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
}

#pragma mark 蓝牙状态Delegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    NSString *strMessage = @"";
    switch (central.state) {
        case CBManagerStatePoweredOn: {
            NSLog(@"蓝牙开启功能可用");
            [self showPrinterManager];
            return;
        }
            break;
        case CBManagerStatePoweredOff: {
            strMessage = @"手机蓝牙功能关闭,请前往设置打开蓝牙及控制中心打开蓝牙";
        }
            break;
        case CBManagerStateUnauthorized:{
            strMessage = @"访问蓝牙权限以用于设备数据读取和发送";
        }
            break;
        case CBManagerStateUnknown:
            break;
        case CBManagerStateResetting:
            break;
        case CBManagerStateUnsupported:
            break;
    }
    //通知没有打开蓝牙的自定义提示弹窗(弹窗代码自行实现)
    [self broadAlertMessage:strMessage];
}

/// 设置弹框
/// @param strMessage 内容
- (void)broadAlertMessage:(NSString *)strMessage{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:strMessage preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *queren = [UIAlertAction actionWithTitle:@"前往设置"
                                                     style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{}completionHandler:^(BOOL  success) {
        }];
    }];
    [alert addAction:cancel];
    [alert addAction:queren];
    [self.navigationController presentViewController:alert animated:YES completion:nil];

}

///  蓝牙开启功能可用打印
- (void)showPrinterManager{
    SEPrinterManager *_manager = [SEPrinterManager sharedInstance];
    if (_manager.isConnected == NO) { // 去连接
        PrinterViewController *printer = [[PrinterViewController alloc] initWithNibName:@"PrinterViewController" bundle:nil];
        [self.navigationController pushViewController:printer animated:YES];
    }else{ // 去打印
        
        HLPrinter *printer = [self getPrinter];
        NSData* imageData = [printer getFinalData];
        // 对象转成字节流 发送给打印机
        kWeakify(self);
        if (imageData.length == 0) {
            [GHSProgressHUD showMessage:@"数据不能为空"];
            return;
        }
        [_manager sendPrintData:imageData completion:^(CBPeripheral *connectPerpheral, BOOL completion, NSString *error) {
            NSLog(@"写入结:%d---错误:%@",completion,error);
            if (completion == YES) {
                [weakSelf sendPrintInfo];
            }
            [GHSProgressHUD showSuccess:error];
        }];
    }

}

我们样式和这个库要求不一样,我是基于这个库 进行打印,然后修改了内部格式和方法,我基于这个库修改了字体的行间距,计算宽度,2行3行4行不同样式时的处理

//行间距
Byte lineSpace[] = {0x1B,0x33,0x50};
/// 小计 三行
- (void)appendSubtotalText:(NSString *)left centerText:(NSString *)center rightText:(NSString *)right isTitle:(BOOL)isTitle
{
    [self setAlignment:HLTextAlignmentLeft];
    [self setFontSize:HLFontSizeTitleSmalle];
    NSInteger offset = 0;
    if (!isTitle) {
        offset = 10;
    }
    
    if (left) {
        [self setText:left];
    }

    CGFloat titleWidth = [right boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 18) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:11 weight:UIFontWeightRegular]} context:nil].size.width;

    if (right) {
        [self setOffset:520 - (titleWidth)];
        [self setText:right];
    }
    
    if (center) {
        [self setOffset:500 - 235];
        [self setText:center];
    }
    
    [self appendNewLine];
    
}
/// 三行 赠送商品
- (void)appendLeftText:(NSString *)left middleText:(NSString *)middle rightText:(NSString *)right isTitle:(BOOL)isTitle
{
    [self setAlignment:HLTextAlignmentLeft];
    [self setFontSize:HLFontSizeTitleSmalle];
    NSInteger offset = 0;
    if (!isTitle) {
        offset = 10;
    }
    
    if (left) {
        [self setText:left];
    }

    CGFloat titleWidth = [right boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 18) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:11 weight:UIFontWeightRegular]} context:nil].size.width;

    if (right) {
        [self setOffset:520 - (titleWidth)];
        [self setText:right];
    }
    
    if (middle) {
        [self setOffset:520 - (titleWidth + 70)];
        [self setText:middle];
    }
    
    [self appendNewLine];
    
}
/// 四行商品 名称 数量 单位 价格
- (void)appendFourLinesText:(NSString *)left middleText:(NSString *)middle rightText:(NSString *)right moneyText:(NSString *)money isTitle:(BOOL)isTitle{
    [self setAlignment:HLTextAlignmentLeft];
    [self setFontSize:HLFontSizeTitleSmalle];
    NSInteger offset = 0;
    if (!isTitle) {
        offset = 10;
    }
    
    if (left) {
        [self setText:left];
    }
    
    CGFloat rightWidth = [right boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 18) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:11 weight:UIFontWeightRegular]} context:nil].size.width;
    if (money) {
        [self setOffset:500 - (rightWidth + 10)];
        [self setText:money];
    }
    
    if (right) {
        [self setOffset:500 - (rightWidth + 10 + 80)];
        [self setText:right];
    }
    
    if (middle) {
        [self setOffset:500 - (rightWidth + 10 + 80 + 80)];
        [self setText:middle];
    }
    
    [self appendNewLine];

}

对打印小票感兴趣的可以看看 蓝牙打印库https://github.com/Haley-Wong/HLBluetoothDemoicon-default.png?t=LA92https://github.com/Haley-Wong/HLBluetoothDemo

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值