Search code examples
iosobjective-cxcodeairprint

Open Print Dialog in App through Xcode?


i am very new to iOS programming and encountered a issue. I have a pdf i want to print off the internet. How do i print this through my app without a third-party app? Also, i have heard about apple's AirPrint, and that it is pre-installed on the iOS device. How would i use that? Thanks.


Solution

  • .H File Code

     #import
        @interface xyviewController : UIViewController <...,UIPrintInteractionControllerDelegate> {
    
        UIPrintInteractionControllerDelegate should be delegate
        }
        -(IBAction)printdoc;
    

    .M File Code

    -(IBAction)printdoc
    {
    
    
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"jpg"];
    NSData *myData = [NSData dataWithContentsOfFile: path];
    
    
    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    
    if(pic && [UIPrintInteractionController canPrintData: myData] ) {
    
    pic.delegate = self;
    
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = [path lastPathComponent];
    printInfo.duplex = UIPrintInfoDuplexLongEdge;
    pic.printInfo = printInfo;
    pic.showsPageRange = YES;
    pic.printingItem = myData;
    
    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
    //self.content = nil;
    if (!completed && error) {
    NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code);
    }
    };
    
    [pic presentAnimated:YES completionHandler:completionHandler];
    
    }
    
    }