How to print in iOS 4.2? - iphone

I want to integrate the print functionality in my app.
The document I want to print will be in .doc or .txt format.
I am not very experienced in iPhone development yet, so finding it difficult to implement it by following the Apple documentation.
If someone could help me by posting some sample code, will be a great help.

Check out the Drawing and Printing Guide for iOS -- I linked to the printing section. There's sample code and good links to more sample code there.
Edit: I see now that you indicate you find the documentation difficult to follow.
Word documents are complicated -- you'll need to parse through the data, which is quite difficult.
Text and HTML are easier. I took Apple's example for HTML and changed it for plain text:
- (IBAction)printContent:(id)sender {
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = self.documentName;
pic.printInfo = printInfo;
UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
initWithText:yourNSStringWithContextOfTextFileHere];
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);
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
} else {
[pic presentAnimated:YES completionHandler:completionHandler];
}
}

First of all add UIPrintInteractionControllerDelegate and create variable
UIPrintInteractionController *printController;
Below code to print all images, documents, excel, powerpoint , pdf files works for me:
[self printItem:SomeData withFilePath:YourFilePath];
In above code you provide your NSData of your document/image and URL (filePath) and below further code of printItem:withFilePath: method
-(void)printItem :(NSData*)data withFilePath:(NSString*)filePath{
printController = [UIPrintInteractionController sharedPrintController];
printController.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [NSString stringWithFormat:#""];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
printController.printInfo = printInfo;
printController.showsPageRange = YES;
//If NSData contains data of image/PDF
if(printController && [UIPrintInteractionController canPrintData:data]) {
printController.printingItem = data;
}else{
UIWebView* webView = [UIWebView new];
printInfo.jobName = webView.request.URL.absoluteString;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
printController.printFormatter = webView.viewPrintFormatter;
}
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if (!completed && error) {
//NSLog(#"FAILED! due to error in domain %# with error code %u", error.domain, error.code);
}
};
// Check wether device is iPad/iPhone , because UIPrintInteractionControllerDelegate has different methods for both devices
if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
[printController presentFromRect:self.view.frame inView:self.view animated:YES completionHandler:completionHandler];
}
else {
[printController presentAnimated:YES completionHandler:completionHandler];
}
}
I hope it will help. Thanks
// For Swift and if you want to just print image
First create IBoutlet for image
#IBOutlet var qrImage : UIImageView?
and then on click of print button just add below code
//In your view controller
#IBAction func printButton(sender: AnyObject) {
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.general
printInfo.jobName = "My Print Job"
// Set up print controller
let printController = UIPrintInteractionController.shared
printController.printInfo = printInfo
// Assign a UIImage version of my UIView as a printing iten
printController.printingItem = self.qrImage?.image
// Do it
printController.present(from: self.view.frame, in: self.view, animated: true, completionHandler: nil)
}

hi this may help you out try it and post if have any query.
-(IBAction)printFromIphone:(id)sender {
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = self.documentName;
pic.printInfo = printInfo;
UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
initWithText:yourNSStringWithContextOfTextFileHere];
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);
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
} else {
[pic presentAnimated:YES completionHandler:completionHandler];
}
}

Related

UIPrintInteractionController background is transparent

I have simple UIPrintInteractionController in a controller that is presnented modally but I am getting transparent background of UIPrintInteractionController. You can see the issue in attached picture,
This is the code I am using to present UIPrintInteractionController,
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
if(!pic){
NSLog(#"Couldn't get shared UIPrintInteractionController!");
return;
}
// We need a completion handler block for printing.
UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if(completed && error)
NSLog(#"FAILED! due to error in domain %# with error code %u", error.domain, error.code);
};
if(pic && [UIPrintInteractionController canPrintData: myData] ) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"]) {
pic.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [_filePath lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
[printInfo setOrientation:UIPrintInfoOrientationPortrait];
pic.printInfo = printInfo;
pic.showsPageRange = YES;
pic.printingItem = myData;
docsScrollView.hidden = YES;
toolBar.hidden = YES;
self.modalPresentationStyle = UIModalPresentationFullScreen;
[pic presentAnimated:YES completionHandler:completionHandler];
}

iOs Printing my Current screen

Currently I am working on a Paint Application for iPhones and iPads. I want to print the current screen display (Drawing) of the screen. Can any body help me in these case ?
Here is the code i have used so far ,
-(void)printImage {
NSString *path = [[NSBundle mainBundle] pathForResource:#"micky" ofType:#"png"];
NSData *dataFromPath = [NSData dataWithContentsOfFile:path];
UIPrintInteractionController *pCon = [UIPrintInteractionController sharedPrintController];
if(pCon && [UIPrintInteractionController canPrintData:dataFromPath]) {
pCon.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [path lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
pCon.printInfo = printInfo;
pCon.showsPageRange = YES;
pCon.printingItem = dataFromPath;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if (!completed && error) {
NSLog(#"Unsuccessfull %# error%u", error.domain, error.code);
}
};
[pCon presentAnimated:YES completionHandler:completionHandler];
}
}
Again , all what i want to know is i should be able to print the Current Window(Drawing, Screen) instead of the Image Micky.png (as in the code)
This code takes a screenshot of the current view and outputs an UIImage of it:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:context];
UIImage *imageFromCurrentView = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

AirPrint for iPhone App

Been trying to get this printing but it doesn't show up in the printer simulator.
This is my code to get it printing:
-(void)printItem:(NSString*)path {
// NSString *path = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"png"];
NSData *dataFromPath = [NSData dataWithContentsOfFile:#"http://www.endnote.com/support/helpdocs/EN%208%20Scripted%20Demo.pdf"];
// path = #"http://www.samplepdf.com/sample.pdf";
path = #"http://www.endnote.com/support/helpdocs/EN%208%20Scripted%20Demo.pdf";
UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];
NSLog(#"Can we print? %#",printController);
// NSLog(#"Secondly, Can we print? %#",[UIPrintInteractionController canPrintURL:[NSURL URLWithString:path]]);
// if(printController && [UIPrintInteractionController canPrintData:dataFromPath]) {
printController.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [path lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
printController.printInfo = printInfo;
printController.showsPageRange = YES;
printController.printingItem = [NSURL URLWithString:path];
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if (!completed && error) {
NSLog(#"FAILED! due to error in domain %# with error code %u", error.domain, error.code);
}
};
[printController presentAnimated:YES completionHandler:completionHandler];
// }
}
The printer options modal pops up and allows me to choose which printer, range, copy and double sided. When I press the range, it knows that the url I'm trying to print out has 4 pages in it. I know this because when I try another url with 1 page, the page range shows 1 page.
Any ideas?
Thanks.

Objective-C code for AirPrint

How can make a IBAction method for printing a UITextView with AirPrint in objective-c?
Check whether printing is available:
if ([UIPrintInteractionController isPrintingAvailable])
{
// Available
} else {
// Not Available
}
Print after button click:
-(IBAction) buttonClicked: (id) sender;
{
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];
}
Originally posted by '87vert' at iPhone Dev SDK: Airprint Tutorial - Simple Print File
The following method uses the name of the file to be printed and also the bar button code from where you want the airprint popup to be shown.
It works for me and im sure will be helpfull
-(void)printJob:(int)jobType:(NSString*)jobName:(UIBarButtonItem *)barButton{
NSString *path;
if ([jobName isEqualToString:#"Printout.png"]) {
path= [self documentsPathForFileName:#"Printout.png"];
}
NSData *mydata=[NSData dataWithContentsOfFile:path];
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
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 *printController, BOOL completed, NSError *error) {
if (!completed && error) {
NSLog(#"Printing could not complete because of error: %#", error);
}
};
[pic presentFromBarButtonItem:barButton animated:YES completionHandler:completionHandler];
}

Print is not working on ipad

my application though paper feed action is called but nothing is printed and paper comes out blank.. I am using the following code for print.
-(IBAction)printButtonAction:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Preview.pdf"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:writableDBPath]];
UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [writableDBPath lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
controller.printInfo = printInfo;
controller.showsPageRange = YES;
controller.printingItem = data;
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);
};
UIViewPrintFormatter *viewFormatter = [documentView viewPrintFormatter];
viewFormatter.startPage = 0;
controller.printFormatter = viewFormatter;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[controller presentFromBarButtonItem:printButton animated:YES
completionHandler:completionHandler];
} else {
[controller presentAnimated:YES completionHandler:completionHandler];
}
}
Thanks
Deepika jain
I think the below code will work,
-(IBAction)printButtonAction:(id)sender{
float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (systemVersion>4.1) {
NSData *myPdfData = [NSData dataWithContentsOfFile:pdfPath]; //check the value inside |myPdfData| and |pdfPath| is the path of your pdf.
UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
if (controller && [UIPrintInteractionController canPrintData:myPdfData]){
controller.delegate = delegate; //if necessary else nil
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [pdfPath lastPathComponent];
//printInfo.duplex = UIPrintInfoDuplexLongEdge;
controller.printInfo = printInfo;
controller.showsPageRange = YES;
controller.printingItem = myPdfData;
// We need a completion handler block for printing.
UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if(completed && error){
NSLog(#"FAILED! due to error in domain %# with error code %u", error.domain, error.code);
}
};
[controller presentFromRect:rect inView:senderView animated:YES completionHandler:completionHandler];
}else {
NSLog(#"Couldn't get shared UIPrintInteractionController!");
}
}
Check the path of the pdf you fetched, I think you missed the '/' after the Documents directory. You try putting a break point and check the path, then check the |data| variable for the content from the path you specified. Try it and respond with ur comments. :)