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

iOS蓝牙连接打印机,打印小票,第1张

我们看看打印出来的效果 

打印小票数据处理,针对服务器返回的数据进行数据封装成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; iunitLength) {
            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

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

/// 赠送信息
- (NSMutableArray *)showGiftData:(PrinterModel *)printModel{
    NSMutableArray *arraygift = [[NSMutableArray alloc]initWithCapacity:0];
    NSInteger  priceLength = 0;
    NSInteger  unitLength = 0;
    NSInteger  countLength = 0;
    
    for (int i=0; iunitLength) {
            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

使用打印功能进行打印

- (void)blueButtonAction{
    
    NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey:@NO};//不d窗(配置)
    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;
    }
    //通知没有打开蓝牙的自定义提示d窗(d窗代码自行实现)
    [self broadAlertMessage:strMessage];
}

/// 设置d框
/// @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/HLBluetoothDemohttps://github.com/Haley-Wong/HLBluetoothDemo

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993744.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)