描述
iOS可以自带打印功能,将文本,图片直接无线连接打印机,并打印出来。分享集成和使用过程。
样式
代码逻辑
文本绘制在UIScrollView上,在将UIScrollView的分割成多个A4大小的图片,最后进行打印,代码逻辑如下:
PrintPaper.m代码
//
// PrintPaper.m
// Learn
//
// Created by skynj on 2024/1/29.
//
#import "PrintPaper.h"
#import "SubjectButton.h"
#import "IOSUtilTool.h"
#import "AppDelegate.h"
#import "FileUtil.h"
@interface PrintPaper ()<UIPrintInteractionControllerDelegate>
@property(nonatomic,assign)float m_a4Width;
@property(nonatomic,assign)float m_a4Height;
@property(nonatomic,assign)float m_subjectWidth;
@property(nonatomic,assign)float m_subjectHeight;
@property(nonatomic,assign)float m_hangHeight;
@property(nonatomic,assign)float m_lieWidth;
@end
static PrintPaper* GV_PrintPaperInstance = nil;
@implementation PrintPaper
+(PrintPaper*) shareInstance{
if (GV_PrintPaperInstance == nil) {
GV_PrintPaperInstance = [[PrintPaper alloc]init];
float rate = 2.0;
float subject_rate = 1.5;
GV_PrintPaperInstance.m_a4Width = 595.0*rate;
GV_PrintPaperInstance.m_subjectWidth = 160.0*subject_rate;
GV_PrintPaperInstance.m_subjectHeight = 50.0*subject_rate;
GV_PrintPaperInstance.m_hangHeight = GV_PrintPaperInstance.m_subjectHeight+20;
GV_PrintPaperInstance.m_lieWidth = GV_PrintPaperInstance.m_subjectWidth + 20;
GV_PrintPaperInstance.m_a4Height = (((int)(824*rate)/(int)GV_PrintPaperInstance.m_hangHeight)+1)*GV_PrintPaperInstance.m_hangHeight ;
}
return GV_PrintPaperInstance;
}
/**
绘制打印的ScrollView
*/
-(UIScrollView*)drawScrollView:(NSMutableArray*)allSujectArray answer:(NSMutableDictionary*)answerDics title:(NSString*)title{
CGSize screenSize = CGSizeMake(self.m_a4Width, self.m_a4Height); //以A4纸像素打印
UIScrollView*g_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)];
float subjectButtonWidth = self.m_subjectWidth;
float subjectButttonHeight = self.m_subjectHeight;
float lieWidth = self.m_lieWidth;
float hangHeight = self.m_hangHeight;
int lie_num = screenSize.width/lieWidth;
float pre_width = (screenSize.width - lieWidth*lie_num)/2.0;
//添加标题
UILabel* g_label = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, screenSize.width-40,hangHeight)];
g_label.backgroundColor = [UIColor clearColor];
g_label.text = title;
g_label.font = [UIFont systemFontOfSize:MAX_FONT];
g_label.textAlignment = NSTextAlignmentCenter;
g_label.textColor = [IOSUtilTool colorWithHexString:BLACK_COLOR];
[g_scrollView addSubview:g_label];
int hang_num = 0;
for (int i = 0; i<[allSujectArray count]; i++) {
int d_lie = i%lie_num;
int d_hang = i/lie_num + 1 ; //默认加上标题行
hang_num = d_hang+1;
SubjectButton* s_button = [[SubjectButton alloc] init];
[s_button initView:CGRectMake(pre_width+d_lie*lieWidth, hangHeight*d_hang, subjectButtonWidth, subjectButttonHeight)];
[g_scrollView addSubview:s_button];
NSMutableArray* g_subject = [allSujectArray objectAtIndex:i];
[s_button setSuject:g_subject];
if (answerDics != nil) { //答案也打印
NSDictionary* answerDic = [answerDics valueForKey:[NSString stringWithFormat:@"%d",i]];
[s_button setAnswer:[answerDic valueForKey:@"true-answer"]];
}
}
int page = (int)(hang_num*hangHeight)/(int)(self.m_a4Height);
if (hang_num*hangHeight != self.m_a4Height*page) { //非 刚好整页书
page++;
}
g_scrollView.contentSize = CGSizeMake(screenSize.width, self.m_a4Height*page);
return g_scrollView;
}
/**
*打印试卷
*/
-(void)printData:(NSMutableArray*)g_imageArray{
UIPrintInteractionController* printer = [UIPrintInteractionController sharedPrintController];
printer.delegate = self;
//配置打印信息
UIPrintInfo *Pinfo = [UIPrintInfo printInfo];
Pinfo.outputType = UIPrintInfoOutputGeneral;//可打印文本、图形、图像
Pinfo.jobName = @"Print Paper";//可选属性,用于在打印中心中标识打印作业
Pinfo.duplex = UIPrintInfoDuplexLongEdge;//双面打印绕长边翻页,NONE为禁止双面
Pinfo.orientation = UIPrintInfoOrientationPortrait;//打印纵向还是横向
// Pinfo.printerID = @"";//指定默认打印机,也可以使用UIPrintInteractionControllerDelegate来知悉
printer.printInfo = Pinfo;
//设置页面范围 打印文字
// UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:@"哈护手霜按时哈哈"];
// textFormatter.startPage = 0;//指定从哪一张开始打印0代表第一张
// textFormatter.contentInsets = UIEdgeInsetsMake(36, 36, 36, 36);//72相当于1英寸,这样设置上下左右的边距都为0.5英寸
// textFormatter.maximumContentWidth = 504;//(72x7.5)相当于打印宽度为7英寸
// printer.printFormatter = textFormatter;
// printer.printingItem = [UIImage imageNamed:@"LaunchImage"];
// NSMutableArray* g_imageArray = [self getImageByCoreGraphics:scrollView];
printer.printingItems = g_imageArray;
// printer.showsPageRange = NO;
[printer presentAnimated:YES completionHandler:^(UIPrintInteractionController * _Nonnull printInteractionController, BOOL completed, NSError * _Nullable error) {
if (!completed && error) {
NSLog(@"Error");
NSMutableDictionary* message_dic = [[NSMutableDictionary alloc]initWithCapacity:2];
NSMutableDictionary* config_dic = [[NSMutableDictionary alloc]initWithCapacity:2];
[config_dic setValue:[NSString stringWithFormat:@"打印失败error:%@",error.description] forKey:@"tipMsg"];
AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[IOSUtilTool toastTip:message_dic config:config_dic superView:delegate.window];
}else if(completed){ //打印完成
[self savePaper]; //保存打印试卷
}else if(!completed){ //取消打印
}
}];
}
-(void)savePaper{
if (self.m_preparePrintDic == nil) {
return;
}
NSString* uuid = [[NSUUID UUID] UUIDString];
[FileUtil writeFile:self.m_preparePrintDic dir:@"paper" fileName:[NSString stringWithFormat:@"%@",uuid]];
NSMutableArray* g_array = [FileUtil readFile:@"printpapers"];
if (g_array == nil) { //还没有创建过papers
g_array = [[NSMutableArray alloc]initWithCapacity:2];
}
NSDate* date = [NSDate date];
NSDateFormatter* g_dateformate = [[NSDateFormatter alloc]init];
[g_dateformate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString* createTime = [g_dateformate stringFromDate:date];
NSMutableDictionary* g_paperDic = [[NSMutableDictionary alloc]initWithCapacity:2];
[g_paperDic setValue:[self.m_preparePrintDic valueForKey:@"paper_title"] forKey:@"title"];
[g_paperDic setValue:createTime forKey:@"create_time"];
[g_paperDic setValue:[NSString stringWithFormat:@"paper/%@",uuid] forKey:@"path"];
[g_array addObject:g_paperDic];
[FileUtil writeFile:g_array dir:@"" fileName:@"printpapers"];
}
- (NSMutableArray*)getImageByCoreGraphics:(UIScrollView*) scrollView {
// 保存当前的偏移量
CGPoint previousContentOffset = scrollView.contentOffset;
CGRect previousFrame = scrollView.frame;
// 将偏移量设置为(0,0)
scrollView.contentOffset = CGPointZero;
scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
// ---------- start -------------
// 申请绘制空间
unsigned char *imageBuffer = (unsigned char *)malloc(4 * scrollView.contentSize.width * scrollView.contentSize.height);
// 绘制上下文
CGContextRef imageContext = CGBitmapContextCreate(NULL, scrollView.contentSize.width, scrollView.contentSize.height, 8, scrollView.contentSize.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);
// 将CoreGraphics转换成UIKit的坐标系,先向下移动整张图片的高度,然后垂直翻转
CGContextTranslateCTM(imageContext, 0.0f, scrollView.contentSize.height);
CGContextScaleCTM(imageContext, 1.0f, -1.0f);
// 渲染全部内容
[scrollView.layer renderInContext:imageContext];
// 生成图片
CGImageRef imageRef = CGBitmapContextCreateImage(imageContext);
// 转换为UIImage
UIImage *image = [UIImage imageWithCGImage:imageRef];
// 注意:释放申请的空间
CGImageRelease(imageRef);
CGContextRelease(imageContext);
free(imageBuffer);
// ---------- end --------------
// 注意:恢复偏移量
scrollView.contentOffset = previousContentOffset;
scrollView.frame = previousFrame;
float pageHeight = self.m_a4Height;
float pageWidth = self.m_a4Width;
float lengthImageHeight = image.size.height;
float lengthImageWidth = image.size.width;
float page = lengthImageHeight/pageHeight;
NSLog(@"imageWidth = %f,imageHeight = %f",image.size.width,image.size.height);
NSMutableArray* g_array = [[NSMutableArray alloc]initWithCapacity:2];
for (int i = 0; i< (int)page; i++) {
float page_y = i* pageHeight;
CGRect pageRect = CGRectMake(0, page_y , pageWidth, pageHeight);
UIImage* g_image = [self imageFromImage:image inRect:pageRect];
[g_array addObject:g_image];
}
return g_array;
}
//绘制原图这个就是将原图改变为A4 纸宽度的图片
- (UIImage*)scaleToSize:(UIImage *)img size:(CGSize)size{
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(20,20,size.width,size.height)];
//从当前context中创建一个改变大小后的图片
UIImage*scaledImage =UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
//返回新的改变大小后的图片
return scaledImage;
}
//截取原图 截取部分 打印的图片就是从这里来
- (UIImage*)imageFromImage:(UIImage*)image inRect:(CGRect)rect{
CGImageRef sourceImageRef = [image CGImage];
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef,rect);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
return newImage;
}
@end
PrintPaper.h代码
//
// PrintPaper.h
// Learn
//
// Created by skynj on 2024/1/29.
//
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
NS_ASSUME_NONNULL_BEGIN
@interface PrintPaper : NSObject
@property(nonatomic,retain)NSMutableDictionary* m_preparePrintDic;
+(PrintPaper*) shareInstance;
/**
绘制打印的ScrollView
*/
-(UIScrollView*)drawScrollView:(NSMutableArray*)allSujectArray answer:(NSMutableDictionary*)answerDic title:(NSString*)title;
- (NSMutableArray*)getImageByCoreGraphics:(UIScrollView*)scrollView;
-(void)printData:(NSMutableArray*)g_imageArray;
@end
NS_ASSUME_NONNULL_END