2013-01-17 69 views
1

嗨,有沒有人可以幫助我?我是iOS開發新手。我試圖實現一個打印功能,但我得到它的錯誤。我只看到.xib文件,其中一些文件是labels。該textview是存在的,我只是想打印圖...當我按下打印按鈕的程序崩潰..在iOS上打印

這裏是我的代碼:

- (NSData *)generatePDFDataForPrinting { 
    NSMutableData *myPdfData = [NSMutableData data]; 
    UIGraphicsBeginPDFContextToData(myPdfData, kPDFPageBounds, nil); 
    UIGraphicsBeginPDFPage(); 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    [self drawStuffInContext:ctx]; // Method also usable from drawRect:. 
    UIGraphicsEndPDFContext(); 
    return myPdfData; 
} 

- (void)drawStuffInContext:(CGContextRef)ctx { 
    UIFont *font = [UIFont fontWithName:@"Zapfino" size:48]; 
    CGRect textRect = CGRectInset(kPDFPageBounds, 36, 36); 
    [@"hello world!" drawInRect:textRect withFont:font]; 
} 


- (IBAction)printFromIphone:(id)sender { 
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue]; 

    if (systemVersion>4.1) { 

     NSData *myPdfData = [NSData dataWithContentsOfFile:myPdfData]; //check the value inside |myPdfData| and |pdfPath| is the path of your pdf. 
     UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController]; 
     if (controller && [UIPrintInteractionController canPrintData:myPdfData]){ 
      //controller.delegate = delegate; //if necessary else nil 
      UIPrintInfo *printInfo = [UIPrintInfo printInfo]; 
      printInfo.outputType = UIPrintInfoOutputGeneral; 
      printInfo.jobName = [myPdfData lastPathComponent]; 
      //printInfo.duplex = UIPrintInfoDuplexLongEdge; 
      controller.printInfo = printInfo; 
      controller.showsPageRange = YES; 
      controller.printingItem = myPdfData; 

      // We need a completion handler block for printing. 
      UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) { 
       if(completed && error){ 
        NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code); 
       } 
      }; 

      //   [controller presentFromRect:CGRectMake(200, 300, 100, 100) inView:senderView animated:YES completionHandler:completionHandler]; 
     }else { 
      NSLog(@"Couldn't get shared UIPrintInteractionController!"); 
     } 
    } 
} 
+0

那麼你得到哪個錯誤? –

+0

使用未聲明的標識符pdfData ....並且你可以建議我任何確切的教程... PLZ ..感謝 –

回答

0

不知道它的一個錯字或不是,但你已經評論了你的實際PDF數據,這是它未申報的原因。

因爲您需要myPdfData,所以此行需要取消註釋。

//NSData *myPdfData = [NSData dataWithContentsOfFile:pdfData]; //check the value inside |myPdfData| and |pdfPath| is the path of your pdf. 

您可以用此行替換它以使用您的pdf而不是文件。

NSData *myPdfData = [self generatePDFDataForPrinting]; 
+0

感謝您的回覆,並再次在下面的方法一個更多的錯誤未聲明的標識符「rect」[控制器presentFromRect:rect inView: senderView動畫:YES completionHandler:completionHandler]; –

+0

你需要從某處出示它。矩形只是位置。你可以用CGRect來填寫你想要顯示的地方。 –