Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 12-16-2010, 08:04 AM   #1 (permalink)
Registered Member
 
twerner's Avatar
 
Join Date: Nov 2009
Location: -
Posts: 299
twerner is on a distinguished road
Default airprint tutorial - simple print file ! < 30 lines of code !!

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
twerner is offline   Reply With Quote
Old 02-04-2011, 03:24 PM   #2 (permalink)
Registered Member
 
Join Date: Feb 2011
Posts: 1
bluewindow99 is on a distinguished road
Default

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....
bluewindow99 is offline   Reply With Quote
Old 03-03-2011, 09:53 PM   #3 (permalink)
Registered Member
 
87vert's Avatar
 
Join Date: Sep 2010
Location: Pittsburgh
Posts: 172
87vert is on a distinguished road
Default

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.

Code:
-(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:

Code:
 if (![UIPrintInteractionController isPrintingAvailable])
    {
}
__________________
Wolfador Coding
Check out my apps:
Crazy Dog Daily Log || Crazy Spouse Daily Log || iCourtReport
87vert is offline   Reply With Quote
Old 07-26-2011, 12:07 PM   #4 (permalink)
Registered Member
 
Join Date: Jul 2011
Posts: 1
Mcmoo is on a distinguished road
Default

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
Mcmoo is offline   Reply With Quote
Old 09-06-2011, 02:58 PM   #5 (permalink)
Registered Member
 
Join Date: Aug 2010
Posts: 236
lilzz is on a distinguished road
Default Why cosign identity under Project and Target settings different?

c

Last edited by lilzz; 09-06-2011 at 03:19 PM.
lilzz is offline   Reply With Quote
Old 10-27-2011, 05:56 AM   #6 (permalink)
Registered Member
 
twerner's Avatar
 
Join Date: Nov 2009
Location: -
Posts: 299
twerner is on a distinguished road
Default

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...
twerner is offline   Reply With Quote
Old 10-27-2011, 06:07 AM   #7 (permalink)
Reading the Documentation
 
baja_yu's Avatar
 
Join Date: Sep 2010
Location: 45.255019,19.844908
Posts: 5,414
baja_yu has a spectacular aura about
Default

Quote:
Originally Posted by twerner View Post
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.
baja_yu is offline   Reply With Quote
Old 10-27-2011, 11:57 AM   #8 (permalink)
Registered Member
 
twerner's Avatar
 
Join Date: Nov 2009
Location: -
Posts: 299
twerner is on a distinguished road
Default

please have look at my code above, what could be wrong ??
twerner is offline   Reply With Quote
Old 10-31-2011, 03:43 PM   #9 (permalink)
Registered Member
 
iphonig's Avatar
 
Join Date: Sep 2009
Location: United States
Posts: 73
iphonig is on a distinguished road
Default

Quote:
Originally Posted by twerner View Post
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?
__________________
Check Out All of Our Apps Here!
iphonig is offline   Reply With Quote
Old 11-01-2011, 03:31 AM   #10 (permalink)
Registered Member
 
twerner's Avatar
 
Join Date: Nov 2009
Location: -
Posts: 299
twerner is on a distinguished road
Default

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:
Code:
 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
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) {
           
            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:
Code:
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:
Code:
 [pic presentAnimated:YES completionHandler:completionHandler];
Checkout:Example will work if you press the UIButton and the printing uipopover pops up !!
twerner is offline   Reply With Quote
Old 12-04-2011, 03:55 PM   #11 (permalink)
Registered Member
 
Join Date: Dec 2011
Posts: 2
stealthypanda11 is on a distinguished road
Default Won't detect printers.

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!
stealthypanda11 is offline   Reply With Quote
Old 12-26-2011, 02:31 PM   #12 (permalink)
Registered Member
 
Join Date: Dec 2011
Posts: 2
stealthypanda11 is on a distinguished road
Default Fixed my Problem

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!
stealthypanda11 is offline   Reply With Quote
Old 12-26-2011, 02:48 PM   #13 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,003
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by stealthypanda11 View Post
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

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 393
9 members and 384 guests
chemistry, daudrizek, HemiMG, jeroenkeij, Kirkout, PavelMik, whitey99
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,665
Threads: 94,120
Posts: 402,898
Top Poster: BrianSlick (7,990)
Welcome to our newest member, daudrizek
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 02:59 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0