嗨,有没有人帮我这个?我是iOS开发的新手。我正在尝试实现打印功能,但我收到了错误。除了.xib
文件和labels
之外,我什么都没看到。 textview
就在那里,我只想打印那个视图......当我按下打印按钮时程序崩溃了..
这是我的代码:
- (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,这就是为什么它未声明的原因。
此行需要取消注释,因为您需要myPdfData
。
//NSData *myPdfData = [NSData dataWithContentsOfFile:pdfData]; //check the value inside |myPdfData| and |pdfPath| is the path of your pdf.
您可以使用此行替换它以使用您的pdf而不是文件。
NSData *myPdfData = [self generatePDFDataForPrinting];