Friday 6 November 2015

Print from an app

Hello,  here I am describing the different way to include printing functionality  in an iOS app .
To add printing support in an app, at a high level we create  a print job, providing either an array of ready to print images and pdf documents, a single image or pdf, an instance of built in print formatter classes or custom print page renderer.

The UIKit API includes eight classes and one formal protocol. There are two ways to include printing in an iOS app:

1) using UIActivityViewController :  This provides simple printing and do not provide any control over printing process.

2) using UIPrintInteractionController: The shared instance of this class provides the ability to specify what should happen when printing. It contains the information about the printjob(UIPrintInfo), and the size of the paper, and the area for the printed content(UIPrintPaper). It can have a reference to UIPrintInteractionControllerDelegate protocol.

To add the priting content , UIPrintInteractionController provides following ways:

1) printngItem:  to print single image or pdf document, set the printingItem property of the UIPrintInteractionController.

2) printingItems : an array of images or documents, set the printingItems property of the UIPrintInteractionController.

3) PageRenderer : provides the complete control over the page layout. To include pageRenderer, we first subclass the PrintPageRenderer and the assign the instance of it to the PrintPageRenderer property of the UIPrintInteractionController.

These properties are mutually exclusive.

The general workflow to support printing in an app is as follows:

1) get the shared instance of  UIPrintInteractionController.

2) (optional) Create a UIPrintInfo object, set attributes such as output type, job name, and print orientation; then assign the object to the printInfo property of the UIPrintInteractionController instance.

3) (optional)Assign a custom controller object to the delegate property.

4) set the one of the four property of the UIPrintInteractionController instance.

5) If the current user- interface idiom is ipad, present the printing interface to the user by calling:
      presentFromBArButtonItem:animated:completionHandler:  or
 
     presentFromRect:inView:animated:completionHandler:

If the idiom is iPhone or iPod touch, call
    presentAnimated:completionHandler:

Example:

1) In custom view controller conform the protocol UIPrintInteractionControllerDelegate

2) get the shared instance of UIPrintInteractionController:
 
     UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];

3) create a print job and assign it to the printInfo property of the UIPrintInteractionController instance.


          printController.delegate = self;
        
        //print info object to supply required info to prinController
        UIPrintInfo *printInfo = [UIPrintInfo printInfo];
        
        printInfo.outputType = UIPrintInfoOutputPhoto;
        printInfo.jobName = @"Print Template";
        
        //  printing info to printController

        printController.printInfo = printInfo;

4) set the pritingItem property of the UIPrintInteractionController instance.
     
     printController.printingItem = [UIImage imageNamed:@"jery1.jpeg"];

5) create a block :

   //create block to handle error
        
        void(^ completionHandler)(UIPrintInteractionController *, BOOLNSError*)=
        ^(UIPrintInteractionController *pic, BOOL completed, NSError *error){
            
            if (!completed && error) {
                NSLog(@"FAILED! Due to error in domain %@ with error code %ld", error.domain,(long)error.code);
            }
        };
6) check for userinterface and present accordingly:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            NSLog(@"user interface is ipad");
            
        }else{
     [printController presentAnimated:YES completionHandler:completionHandler];
}

7) implement the delegate method;

- (void)printInteractionControllerDidFinishJob:(UIPrintInteractionController *)printInteractionController{    
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Template" message:@"Your template is ready to pickup" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alert show];
    
}


Print Directly:

Alternatively we can print directly without presenting the printing user interface. iOS 8 provides a way to do this. To direct print, conform to the UIPrinterPickerControllerDelegate,  and add the following code:

-(void)searchPrinters{
   
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) {
        UIPrinterPickerController *printerPicker = [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:nil];
        
        [printerPicker presentAnimated:YES completionHandler:^(UIPrinterPickerController *printer, BOOL userDidSelect,NSError * error){
         
            if (userDidSelect) {
                [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:printer.selectedPrinter];
                
            printerURL = printer.selectedPrinter.URL;
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                
                [defaults setObject:[printerURL absoluteStringforKey:@"printerURL"];
                
                [defaults synchronize];
            }
            
        }];
    }
}

-(IBAction)print:(id)sender{

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
                
                    self.selectedPrinter = [UIPrinter printerWithURL:[NSURL URLWithString:[defaults objectForKey:@"printerURL"]] ];
                
                    if (self.selectedPrinter) {
                        
                        [printController printToPrinter:self.selectedPrinter completionHandler:^(UIPrintInteractionController *printController, BOOL completed, NSError *error){
                        
                            if (completed) {
                                NSLog(@"priting successfully completed");
                                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print" message:@"Successfully printed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nilnil ];
                                
                                [alert show];
                            }
                            else{
                                NSLog(@"error occured while printing");
}

}




Reference:https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/Printing/Printing.html

No comments:

Post a Comment