2016-05-13 56 views
0

我想添加兩個NSAttributedStrings在一起。我希望它能打印出來,這樣標題的字體大小和字體就不同於印刷體。這是我正在使用的代碼。AirPrint與NSAttributedString

-(IBAction)print:(id)sender{ 
    UIFont *font = [UIFont fontWithName:@"Avenir Next Condensed" size:16.0]; 
     NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font 
                    forKey:NSFontAttributeName]; 
     NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"this is the title" attributes:attrsDictionary]; 


UIFont *font2 = [UIFont systemFontOfSize:14.0]; 

NSDictionary *attrsDictionary2 = [NSDictionary dictionaryWithObject:font2 forKey:NSFontAttributeName]; 

     NSAttributedString *body = [[NSAttributedString alloc] initWithString:@"this is the body of the print" attributes:attrsDictionary2]; 

      NSMutableString *printBody = [NSMutableString stringWithFormat:[NSString stringWithFormat:@"%@ \n" 
@"%@ \n",title,body]]; 

      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; 

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

     } 

當我打印這個打印機時,打印機打印出一個看起來像這樣的消息,它只是表示所有的字體數據。

This is a test title{ 
NSFont = <font data> 
} 
this is the body of the print 

如果有人能幫上忙,那就太好了!

+0

你爲什麼不嘗試,並打印出來以HTML格式? –

回答

1

這條線:

NSMutableString *printBody = [NSMutableString stringWithFormat:[NSString stringWithFormat:@"%@ \n%@ \n",title,body]]; 

並沒有真正太大的意義。請記住,當您以字符串格式使用%@時,其值會來自調用相應對象的description方法。這不是組合兩個屬性字符串的正確方法。

所以你需要解決的第一件事是組合兩個屬性字符串。你想:

NSAttributedString *newline = [[NSAttributedString alloc] initWithString:@"\n"]; 
NSMutableAttributedString *printBody = [title mutableCopy]; 
[printBody appendAttributedString:newline]; 
[printBody appendAttributedString:body]; 
[printBody appendAttributedString:newline]; 

既然你有你想打印的正確的歸因字符串,你需要改變你如何創建打印格式化程序。相反的:

UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody]; 

你想:

UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithAttributedText:printBody];