AriPrint
2018-04-04 本文已影响14人
wpf_register
参考文档1
参考文档2
目前多数打印机已经可以支持苹果的AirPrint功能,刚完成的项目使用的打印机自身有相应的SDK ,但相比苹果原生方法就显得麻烦了很多。
- 生成打印图片
PrintView * printView = [[PrintView alloc] initWithFrame:CGRectMake(0, 0, 3140, 1310) Model:model];
[self.view addSubview:printView];
// 将视图添加在控制器上,供截图使用
UIImage* tempShotImage = [self screenShotImageWithSize:CGSizeMake(3140, 1310) View:printView];
// 得到视图图层的图片,供打印使用
[printView removeFromSuperview];
// 截图完成后,移除视图
[imageArr addObject:tempShotImage];
截图
-(UIImage*)screenShotImageWithSize:(CGSize)ImageSize View:(UIView*)contentView{
UIGraphicsBeginImageContext(ImageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
[contentView.layer renderInContext:context];
// renderInContext 不安全
// drawViewHierarchyInRect 与 renderInContext 功能相同
// [contentView drawViewHierarchyInRect:CGRectMake(0, 0, ImageSize.width, ImageSize.height) afterScreenUpdates:YES];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- 开始打印
//图片以数组形式传递
[PrintManager printImageWithArr:imageArr
ViewController:self
ShowRect:CGRectMake(0, 0, 1300, 200)];
打印方法
+(void)printImageWithArr:(NSArray*)imageArr
ViewController:(UIViewController<UIPrintInteractionControllerDelegate>*)viewController
ShowRect:(CGRect)showRect{
NSMutableArray* printItems = [NSMutableArray arrayWithCapacity:0];
for (UIImage* image in imageArr) {
NSData* imageData = UIImagePNGRepresentation(image);
// 得到打印数据
[printItems addObject:imageData];
}
UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];
if(printController && [UIPrintInteractionController canPrintData: printItems[0]] ) {
printController.delegate = viewController;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = @"ZBY";
printInfo.duplex = UIPrintInfoDuplexLongEdge;
printController.printInfo = printInfo;
printController.showsPageRange = NO;
printController.printingItems = printItems;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
if (completed)
{
// 执行成功后的处理
}
else if (!completed && error)
{
// 执行失败后的处理
}
};
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[printController presentAnimated:YES completionHandler:completionHandler];
// iPhone使用这个方法
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
[printController presentFromRect:showRect inView:viewController.view animated:YES completionHandler:completionHandler];
// iPad使用这个方法
}
}
}
PS: 如果在项目中做成无交互的打印效果可能会更好一些。