【问题标题】:automatic AirPrint IOS自动 AirPrint IOS
【发布时间】:2025-12-04 02:25:02
【问题描述】:

我需要在后台在 Xcode 中进行 AirPrint,无需用户交互。我不在乎是否必须使用 3rd 方框架来执行此操作。这是我拥有但需要用户交互的代码。

 NSMutableString *printBody = [NSMutableString stringWithFormat:@"%@",TextField.text];

    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;


    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = @"PrintJob";
    pic.printInfo = printInfo;


    UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody];
    textFormatter.startPage = 0;
    textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0);
    textFormatter.maximumContentWidth = 6 * 72.0;
    pic.printFormatter = textFormatter;
    pic.showsPageRange = YES;


void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
    if (!completed && error) {
        NSLog(@"Printing could not complete because of error: %@", error);
    }
};


    [pic presentAnimated:YES completionHandler:completionHandler];

如果有人能帮忙那就太好了!

【问题讨论】:

标签: ios objective-c printing airprint


【解决方案1】:

I found a video that helped a lot!这是 iOS 8 的 wwdc 视频,他们刚刚介绍了不使用 UIPrintInteractionController 的新打印方式。这里是。

    -(IBAction)print:(id)sender{

      NSMutableString *printBody = [NSMutableString stringWithFormat:@"Hey this is a test lets hope it works!"];

      UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
      pic.delegate = self;


      UIPrintInfo *printInfo = [UIPrintInfo printInfo];
      printInfo.outputType = UIPrintInfoOutputGeneral;
      printInfo.jobName = @"PrintJob";
      pic.printInfo = printInfo;


      UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody];
      textFormatter.startPage = 0;
      textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0);
      textFormatter.maximumContentWidth = 6 * 72.0;
      pic.printFormatter = textFormatter;
      pic.showsPageRange = YES;
//save your printer using code also in video. 

      UIPrinter *SavedPrinterUserDefaults = [[NSUserDefaults standardUserDefaults]
                                             objectForKey:@"SavedPrinter"];
      [pic printToPrinter:SavedPrinterUserDefaults
        completionHandler:^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
          if (completed && !error)
            NSLog(@"YAYA! it printed");
        }];

    }

我希望这可以帮助任何有同样问题的人。 Here is more to read about what you can do with this new API!

【讨论】: