Printing documents from app programmatically

Print documents programmatically in IOS SDK - AirPrint - Tutorial

Printing from IOS device can only be done using Air-printer. There is very simple code provide by Apple Inc., to let developers initiate direct print command from their apps. In this post we will learn about printing documents from IOS app programmatically.

We can use UIPrintInteractionController class for printing documents programmatically from IOS app. Below is the code that we used in one of our app for printing pdf files

Source code to print documents programmatically using airprinter
UIPrintInteractionController *pc = [UIPrintInteractionController sharedPrintController];
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.orientation = UIPrintInfoOrientationPortrait;
    printInfo.jobName =@”Report”;
    pc.printInfo = printInfo;
    pc.showsPageRange = YES;
    pc.printingItem = [NSURL fileURLWithPath:[self returnFilePath]];
    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if(!completed && error){
            NSLog(@”Print failed – domain: %@ error code %ld”, error.domain, (long)error.code);
        }
    };
    [pc presentFromRect:printButton.frame inView:self.view animated:YES completionHandler:completionHandler];

In above code, First we create an object of UIPrintInteractionController. Then we need to give some information about printing to the printer. For this we can use UIPrintInfo class and set print info properties as per our requirement.

Here, we gave our pdf file path stored in document directory to the printing item, printingItem property of UIPrintInteractionController can take values of type NSData, NSUrl, UIImage and ALAsset.

After giving our item to be printed by air printer using printingItem property we can set callback handler of our printer job that tells us wether its a success or failure.

Last step is to present our UIPrintInteractionController to the user.

NOTE: printButton is our UIButton object.

You will something like as shown in picture below after implementing the above code.

UIPrintInteractionController - Printing to Air-printer