iOS 藍牙連接打印銀行叫號單子

先看一下打印出來的效果:


WechatIMG475.jpeg

然后說我遇到的問題:
第一個問題:
打印機型號不好說鳍烁,所有的包裝盒蹲缠、說明書和機器上都是英文MPT-II斋射。同事說是從賣家手里買的,沒有客服蕾额,不能找他們解決問題早芭。里面有個光盤,里面有一些exe文件和iOS demo诅蝶,可是退个,這個demo運行報錯募壕!


WechatIMG344.png

報錯的是開發(fā)商提供的print.framework,這報錯我直接放棄了他的demo语盈。從GitHub上找了一些藍牙打印小票的demo舱馅,試了一下,都能連接這個打印機刀荒。但是呢代嗤,打印出來的中文都是亂碼。最后缠借,有兩個編碼需要設(shè)置
第一個看下面代碼干毅,第二個就是UTF-8
- (void)setText:(NSString *)text
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *data = [text dataUsingEncoding:enc];
    [_printerData appendData:data];
}
WX20190511-152337.png

第二個問題:
打印出來的亂碼,我就覺得是編碼問題烈炭,但是把編碼格式都試了一下溶锭,浪費了很多紙,打印出來還是亂碼符隙。
我就用光盤里面的軟件刷入了一下字體趴捅。


WechatIMG26.jpeg

刷入之后,可以了霹疫,但是打印出來的有問題拱绑。


WechatIMG450.jpeg

打印出來的有兩個問題,1丽蝎、字體都一樣大猎拨,也沒有粗體設(shè)置;2屠阻、圖片打印出來的效果都是下面有一部分缺失了红省。。国觉。

第三個問題:打印出來大字吧恃,圖片不缺失
先解決打印出來的粗體和大字,刷入一下


222.jpeg

刷入之后呢麻诀,字體只是變粗了一些而已痕寓,設(shè)置字號0x77,7倍大就是打印不出來。
我就放棄了這種打印出來大字體的想法蝇闭。
那應(yīng)該怎么做才能打印出來大大的叫號呢呻率?
圖片,對呻引,把K017弄成圖片礼仗。

#pragma mark - view生成image 高清方法
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

做法很簡單,就是寫一個UIView

這個代碼我就不寫了,寫一個白背景色的UIView藐守,放進去一個UILabel挪丢,設(shè)置字號50,加粗卢厂,居中(記得把生成的圖片保存到相冊,以便參考對比)
WechatIMG177.jpeg

就是這個效果了惠啄。
下面解決慎恒,圖片不缺失了。我就想著撵渡,我打印了兩個圖片下面都缺失了融柬,那我都把他們放進我的UIView里面,全部打印出來趋距,下面設(shè)置大的空白footer粒氧,就不會缺失了吧。


WechatIMG178.jpeg

嘿嘿嘿节腐,這樣可以了吧外盯,看??:


111.jpeg

這是什么鬼啊,出現(xiàn)亂碼翼雀,是因為沒有藍牙傳輸沒有分包嗎饱苟,我車看了代碼,有分包處理代碼狼渊。百度半天箱熬,可能這個包設(shè)置的有點大,我看了一下是146狈邑,提示必須設(shè)置偶數(shù)哦城须,我就改的小一點128試試,這個數(shù)字比較有感覺米苹。
跟我猜想的一樣糕伐,打印出來很完整的圖片。但是有一個重大的問題就是驱入,打印很慢赤炒,一卡一卡的,突突突的才打印出來亏较,而且打印出來的下面說明文字很小莺褒,基本看不清,我就放棄了打印一整張圖片的想法雪情。

第四個問題:尋找最優(yōu)解
把圖片分開打印遵岩,多次嘗試之后,決定,把銀行l(wèi)ogo和叫號生成新的圖片來打映局础:


WechatIMG176.jpeg

下面文字的用text方式打印舍哄,第二張圖片直接打印,因為我沒找到demo里面可以任意布局的方法誊锭,把二維碼和電話分開打印表悬,最終效果就是我的第一張圖片。
下面上關(guān)鍵代碼:

//這段代碼放進AppDelegate.m丧靡,如果之前連接打印成功了蟆沫,再次打開App之后,就可以直接打印温治,不用再手動連接饭庞。
 //自動重連打印機
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
//為什么用IDFV呢,自己體會吧熬荆,作用很大舟山。
    if (![[SEPrinterManager sharedInstance] isConnected]&&[[NSUserDefaults standardUserDefaults]boolForKey:idfv]) {
        [[SEPrinterManager sharedInstance] autoConnectLastPeripheralTimeout:10 completion:^(CBPeripheral *perpheral, NSError *error) {
            //這里不需要處理是否出錯
        }];
    }
-(void)StartPrint{
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if ([[NSUserDefaults standardUserDefaults]boolForKey:idfv]) {
        [self OnlinePrint];
    }else{
        HBPrintViewController *vc=[[HBPrintViewController alloc]init];
        vc.printer=[self getPrinter];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self.viewController presentViewController:vc animated:YES completion:^{
            vc.view.backgroundColor=[UIColor colorWithWhite:0.9 alpha:0.1];
        }];
    }
}
//已經(jīng)連接過的藍牙設(shè)備開始打印,如果completion為NO卤恳,重新初始化發(fā)起藍牙連接
-(void)OnlinePrint{
    HLPrinter *printer = [self getPrinter];
    
    NSData *mainData = [printer getFinalData];
    [[SEPrinterManager sharedInstance] sendPrintData:mainData completion:^(CBPeripheral *connectPerpheral, BOOL completion, NSString *error) {
        NSLog(@"寫入結(jié)果:%d:%@",completion,error);
        if (!completion) {
            //重新發(fā)起初始化 設(shè)置NO
            NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:idfv];
            [self StartPrint];
        }
    }];
}
- (HLPrinter *)getPrinter
{
    HLPrinter *printer = [[HLPrinter alloc] init];
    UIView *myView=[[UIView alloc]init];
    myView.backgroundColor=[UIColor whiteColor];
    myView.frame=CGRectMake(0, 0, 420, 250);
    UIImage *img1=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Print1" ofType:@"pic"]];
    UIImageView *imgV1 = [[UIImageView alloc]initWithImage:img1];
    imgV1.frame=CGRectMake(10, 10, 400, 100);
    [myView addSubview:imgV1];
    UILabel *l=[[UILabel alloc]initWithFrame:CGRectMake(150, 150, 120, 60)];
    l.text=self.model.queueNum;
    l.font=[UIFont boldSystemFontOfSize:50];
    l.textAlignment=NSTextAlignmentCenter;
    l.textColor=[UIColor blackColor];
    [myView addSubview:l];
    UIImage *MYimg=[self makeImageWithView:myView withSize:CGSizeMake(420, 250)];
    UIImageWriteToSavedPhotosAlbum(MYimg, nil, nil, nil);
    [printer appendImage:MYimg alignment:HLTextAlignmentCenter maxWidth:368];
    
    [printer appendText:[NSString stringWithFormat:@"等待人數(shù):%@",self.model.waitNum] alignment:HLTextAlignmentLeft];
    [printer appendText:[NSString stringWithFormat:@"網(wǎng)點名稱:%@",self.model.orgName] alignment:HLTextAlignmentLeft];
    [printer appendText:[NSString stringWithFormat:@"取號時間:%@",self.model.printTime] alignment:HLTextAlignmentLeft];
    [printer appendText:@"請您在休息區(qū)等候累盗,注意呼號及電視屏幕顯示信息,如果過號纬黎,請您重新排號幅骄。" alignment:HLTextAlignmentLeft];
    UIImage *img2=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Print0" ofType:@"pic"]];
    [printer appendImage:img2 alignment:HLTextAlignmentCenter maxWidth:368];
    
    return printer;
}
#pragma mark - view生成image 高清方法
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
//HBPrintViewController.m
#import "HBPrintViewController.h"

@interface HBPrintViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic)  UITableView *tableView;

@property (strong, nonatomic)   NSArray  *deviceArray;  /**< 藍牙設(shè)備個數(shù) */
@property (strong, nonatomic)  UIViewController *presentingVC;

@end

@implementation HBPrintViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.edges.equalTo(self).insets(UIEdgeInsetsMake(165, 260, 130, 260));
    }];
    SEPrinterManager *_manager = [SEPrinterManager sharedInstance];
    [_manager startScanPerpheralTimeout:10 Success:^(NSArray<CBPeripheral *> *perpherals,BOOL isTimeout) {
        NSLog(@"perpherals:%@",perpherals);
        _deviceArray = perpherals;
        [_tableView reloadData];
    } failure:^(SEScanError error) {
        NSLog(@"error:%ld",(long)error);
    }];
    
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]init];
        _tableView.layer.cornerRadius=10;
        UIView *v1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 60)];
        v1.backgroundColor=[UIColor whiteColor];
        UILabel *l=[[UILabel alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 40)];
        l.text=@"請點擊您想連接的藍牙設(shè)備";
        l.backgroundColor=[UIColor lightGrayColor];
        [v1 addSubview:l];
        _tableView.tableHeaderView=v1;
    }
    return _tableView;
}
//點別的地方返回之前頁面
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.presentingVC) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else
    {
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    }
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _deviceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"deviceId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    
    CBPeripheral *peripherral = [self.deviceArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"名稱:%@",peripherral.name];
    cell.imageView.image = [UIImage imageNamed:@"blue"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CBPeripheral *peripheral = [self.deviceArray objectAtIndex:indexPath.row];
    dispatch_queue_t queue =  dispatch_queue_create("連接藍牙直接打印", NULL);
    dispatch_async(queue, ^{
        [[SEPrinterManager sharedInstance] fullOptionPeripheral:peripheral completion:^(SEOptionStage stage, CBPeripheral *perpheral, NSError *error) {
            if (!error) {
                NSLog(@"連接藍牙設(shè)備成功,但不一定是我的打印機哦");
            }
            if (stage == SEOptionStageSeekCharacteristics) {
                NSData *mainData = [self.printer getFinalData];
                [[SEPrinterManager sharedInstance] sendPrintData:mainData completion:^(CBPeripheral *connectPerpheral, BOOL completion, NSString *error)
                 {
                     if (completion) {
                         NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
                         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:idfv];
                     }
                 }];
            }
        }];
    });
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 重寫dismiss解決方案
-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
{
    if (self.presentedViewController)
    {
        if (self.presentingViewController) {
            self.presentingVC = self.presentingViewController;
        }
        [super dismissViewControllerAnimated:flag completion:completion];
    }
    
}
.h文件

#import <UIKit/UIKit.h>
#import "SEPrinterManager.h"

NS_ASSUME_NONNULL_BEGIN

@interface HBPrintViewController : UIViewController
@property(nonatomic , strong)HLPrinter *printer;

@end

NS_ASSUME_NONNULL_END

好了本今,到此我的關(guān)鍵代碼全在這里了拆座,至于引用的東西GitHub上就有。

完冠息,求贊求評論求喜歡挪凑,銀行信息這次不打碼了,就是這么任性逛艰!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末躏碳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子散怖,更是在濱河造成了極大的恐慌菇绵,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件镇眷,死亡現(xiàn)場離奇詭異咬最,居然都是意外死亡,警方通過查閱死者的電腦和手機欠动,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門永乌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來惑申,“玉大人,你說我怎么就攤上這事翅雏∪ν眨” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵望几,是天一觀的道長绩脆。 經(jīng)常有香客問我,道長橄妆,這世上最難降的妖魔是什么衙伶? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮害碾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘赦拘。我一直安慰自己慌随,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布躺同。 她就那樣靜靜地躺著阁猜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蹋艺。 梳的紋絲不亂的頭發(fā)上剃袍,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天,我揣著相機與錄音捎谨,去河邊找鬼民效。 笑死,一個胖子當(dāng)著我的面吹牛涛救,可吹牛的內(nèi)容都是我干的畏邢。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼检吆,長吁一口氣:“原來是場噩夢啊……” “哼舒萎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起蹭沛,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤臂寝,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后摊灭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體咆贬,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年斟或,在試婚紗的時候發(fā)現(xiàn)自己被綠了素征。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖御毅,靈堂內(nèi)的尸體忽然破棺而出根欧,到底是詐尸還是另有隱情,我是刑警寧澤端蛆,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布凤粗,位于F島的核電站,受9級特大地震影響今豆,放射性物質(zhì)發(fā)生泄漏嫌拣。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一呆躲、第九天 我趴在偏房一處隱蔽的房頂上張望异逐。 院中可真熱鬧,春花似錦插掂、人聲如沸灰瞻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽酝润。三九已至,卻和暖如春璃弄,著一層夾襖步出監(jiān)牢的瞬間要销,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工夏块, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留疏咐,地道東北人。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓拨扶,卻偏偏與公主長得像凳鬓,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子患民,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354