Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

airprint tutorial - simple print file ! < 30 lines of code !!

twernertwerner Posts: 414New Users @ @
edited December 2011 in iPhone SDK Development
After days of google and brilliant help from an user of this forum and studying the xcode 4.2 example photoprint, i managed to print much easier via a simple ibaction and a predefined local resource file, here is the code -
sdk 4.2, uikit framework included,demo.jpg is a local resource file could be also a pdf or doc file instead:

and think different and above all think simple!!!!

in .h:
#import <UIKit/UIKit.h>
@interface xyviewController : UIViewController <...,UIPrintInteractionControllerDelegate> {

UIPrintInteractionControllerDelegate should be delegate
}
-(IBAction)printdoc;
in .m:

-(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];

}

}

Note: for testing on hardware device, be sure airport is enabled and logged to printing wifi network, if you use a shared usb printer on a mac - enable sharing (think of AirPrintHacktivator if you can't share your usb printer) real wifi printer work should work without problems.
If the no airprint printer is available in the wifi network printing popover will not be shown and if you are pressing the ibaction button nothing happens !!!

hope it helps you
Tobias
Post edited by twerner on

Replies

  • bluewindow99bluewindow99 Posts: 1New Users
    edited February 2011
    Very nice, thank you! I see my next problem will be how to place a file on my iPhone that I can print! I'm a newb....
  • 87vert87vert Posts: 173Registered Users
    edited March 2011
    Thanks for the tutorial

    Here is my code for putting in Airprint into my iPad app. It is activated from an Actionsheet. It is grabbing the strings from two UITextViews and printing.
    -(void)printdoc
    {
        NSMutableString *printBody = [NSMutableString stringWithFormat:@"%@, %@",self.encoded.text, self.decoded.text];
        [printBody appendFormat:@"\n\n\n\nPrinted From *myapp*"];
        
         UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
         pic.delegate = self;
         
         UIPrintInfo *printInfo = [UIPrintInfo printInfo];
         printInfo.outputType = UIPrintInfoOutputGeneral;
         printInfo.jobName = self.titleLabel.text;
         pic.printInfo = printInfo;
         
         UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody];
         textFormatter.startPage = 0;
         textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
         textFormatter.maximumContentWidth = 6 * 72.0;
         pic.printFormatter = textFormatter;
         [textFormatter release];
         pic.showsPageRange = YES;
         
         void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
         ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
         if (!completed && error) {
         NSLog(@"Printing could not complete because of error: %@", error);
         }
         };
      
        [pic presentFromBarButtonItem:self.rightButton animated:YES completionHandler:completionHandler];
            
    }
    

    Check if printing is supported with:
    if (![UIPrintInteractionController isPrintingAvailable])
        {
    }
    
    <a href="http://www.wolfador.com" target="_blank">Wolfador Coding</a><br />
    Check out my apps:<br />
    <a href="http://itunes.apple.com/app/crazy-dog-daily-log/id416258866?mt=8" target="_blank">Crazy Dog Daily Log</a> || <a href="http://itunes.apple.com/u
  • McmooMcmoo Posts: 1New Users
    edited July 2011
    Hi

    ive got the print function to work on my app with the demo png but i would like to print text written on a UITextview. Thanks really stuck
  • lilzzlilzz Posts: 240Registered Users @ @
    edited September 2011
  • twernertwerner Posts: 414New Users @ @
    edited October 2011
    It seem that my code above, does not work under iOS 5.0 even if compiled for 4.x the uipopover for printing does not open under iOS 5.0 !!!
    I'm working on it...
  • baja_yubaja_yu Posts: 6,188Moderators, Registered Users Admin
    edited October 2011
    twerner wrote: »
    It seem that my code above, does not work under iOS 5.0 even if compiled for 4.x the uipopover for printing does not open under iOS 5.0 !!!
    I'm working on it...

    Does the Apple sample code for printing work on iOS 5? If there are compatibility issues I'm sure they update the sample to address the issue.
  • twernertwerner Posts: 414New Users @ @
    edited October 2011
    please have look at my code above, what could be wrong ??
  • iphonigiphonig Posts: 73Registered Users
    edited October 2011
    twerner wrote: »
    After days of google and brilliant help from an user of this forum and studying the xcode 4.2 example photoprint, i managed to print much easier via a simple ibaction and a predefined local resource file, here is the code -
    sdk 4.2, uikit framework included,demo.jpg is a local resource file could be also a pdf or doc file instead:

    and think different and above all think simple!!!!

    in .h:
    #import <UIKit/UIKit.h>
    @interface xyviewController : UIViewController <...,UIPrintInteractionControllerDelegate> {

    UIPrintInteractionControllerDelegate should be delegate
    }
    -(IBAction)printdoc;
    in .m:

    -(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];

    }

    }

    Note: for testing on hardware device, be sure airport is enabled and logged to printing wifi network, if you use a shared usb printer on a mac - enable sharing (think of AirPrintHacktivator if you can't share your usb printer) real wifi printer work should work without problems.
    If the no airprint printer is available in the wifi network printing popover will not be shown and if you are pressing the ibaction button nothing happens !!!

    hope it helps you
    Tobias

    Very cool! Would this work to print a local pdf file?
    <a href="http://bit.ly/iPhonigApps" target="_blank">Check Out All of Our Apps Here!</a>
  • twernertwerner Posts: 414New Users @ @
    edited November 2011
    After some time of research (my neck hurts) i have found out the following:

    My 30 lines KISS code does not work on iOS 5.x anymore even if it is compiled for iOS 4.0 on the iPad. It seems to work fine for iPhones iOS 5.0 but also not on universal apps.

    The reason is simple but was hard to find, as there are not many tutorials for AirPrint and iOS 5.0, exactly zero ones...

    Starting with iOS 5.0 you have to check on which device you are running your printing request ! This is actually done by:
     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            [pic presentFromBarButtonItem:self.printButton animated:YES
                completionHandler:completionHandler];
            } else {
            [pic presentAnimated:YES completionHandler:completionHandler];
    

    God knows why Apple changed this in IOS 5.0 - this will be a problem for all universal apps and iPad only apps like mine !!

    So I make it simple and transfer it again to the KISS principal for an iPad only app:

    in the .h file add:
    IBOutlet UIBarButtonItem *printButton;
    @property (retain, readwrite) UIBarButtonItem *printButton;
    in the .m file add:

    // Don't forget to connect your UIBarbuttonitem in xbuilder with the file's owner
    -(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) {
               
                if (!completed && error)
                    NSLog(@"FAILED! due to error in domain %@ with error code %u",
                          error.domain, error.code);
            };
           // iPad only printing
            [pic presentFromBarButtonItem:self.printButton animated:YES
                        completionHandler:completionHandler];
            }
    }
    
    

    For an universal app you have to change the line below // iPad only printing to the following lines:
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            [pic presentFromBarButtonItem:self.printButton animated:YES
                completionHandler:completionHandler];
            } else {
            [pic presentAnimated:YES completionHandler:completionHandler];
        }
    

    or for an iPhone only app like in the first <30 line example:
     [pic presentAnimated:YES completionHandler:completionHandler];
    

    Checkout:Example will work if you press the UIButton and the printing uipopover pops up !!
  • stealthypanda11stealthypanda11 Posts: 2New Users
    edited December 2011
    When I click "Select Printer", it says "Looking for Printers..." for a few seconds and then says "No Printers Found". I'm running your iPad only version, and it works great until this part! Like you said, there's little to no tutorials online, so I was hoping you could give me some feedback! Thanks!
  • stealthypanda11stealthypanda11 Posts: 2New Users
    edited December 2011
    Just in case anyone else was stuck on that same issue, I found out that you have to download Airprint Activator on your computer in order to share the printer with iOS devices. You can find several tutorials online for it, and it should fix that problem of not being able to find these hidden printers. Thanks for the code though!
  • Duncan CDuncan C Posts: 9,021Tutorial Authors, Registered Users @ @ @ @ @ @ @
    edited December 2011
    Just in case anyone else was stuck on that same issue, I found out that you have to download Airprint Activator on your computer in order to share the printer with iOS devices. You can find several tutorials online for it, and it should fix that problem of not being able to find these hidden printers. Thanks for the code though!


    There's also Printopia, the one I use. It's commercial, and costs like 15 dollars. It's well worth it. It also lets you save to a folder on your Mac or to your DropBox, if you have one.
    Regards,
    Duncan C
    WareTo

    widehead.gif
    Animated GIF created with Face Dancer, available for free in the app store.

    I'm available for one-on-one help at CodeMentor
  • Bhavesh_NayiBhavesh_Nayi Posts: 1New Users
    NIce But which library use in code
    plz reply immediatly
  • Duncan CDuncan C Posts: 9,021Tutorial Authors, Registered Users @ @ @ @ @ @ @

    NIce But which library use in code
    plz reply immediatly

    Please calm down immediately. Demanding immediate replies does nothing other than annoy your readers and make them want to ignore you.

    You don't need a third party library. Print support is built into iOS. Your search term in the Xcode docs is "Drawing and Printing Guide for iOS"
    Regards,
    Duncan C
    WareTo

    widehead.gif
    Animated GIF created with Face Dancer, available for free in the app store.

    I'm available for one-on-one help at CodeMentor
Sign In or Register to comment.