24

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.

Kurt Pfeifle
  • 86,724
  • 23
  • 248
  • 345
iPhoneDev
  • 1,547
  • 2
  • 13
  • 36

3 Answers3

34

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];
    }
}
Matthew Frederick
  • 22,245
  • 10
  • 71
  • 97
  • thanx sir for spending ur valuable time to answer my question. – iPhoneDev Dec 08 '10 at 05:59
  • @Matthew: Please edit ur ans. for the line [pic presentFromFromBarButtonItem:sender animated:YES completionHandler:completionHandler]; There should be one 'From' in the "presentFromFromBarButtonItem" method – iPhoneDev Dec 08 '10 at 06:01
  • Made the change. I'm glad it helped. – Matthew Frederick Dec 08 '10 at 06:04
  • @Matthew Frederick: did you have problems with the newline? I'm trying to print the content of a uitextview, but the printer simulator prints it all in one line. If I replace "\n" with "\n\n", the result isn't always the same on the printer simulator. – Sefran2 May 31 '11 at 07:37
  • @Fran Sorry, never used the code myself, just provided it from the sample. – Matthew Frederick May 31 '11 at 07:41
2

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)
}
Maishi Wadhwani
  • 1,104
  • 15
  • 24
  • Hiii, I have a ViewController having QRCode Image and a button with name "print" i want to print that image when i click "print" button.Could u help me in swift i have no idea about it @Maishi Sajnani – Dilip Tiwari Aug 29 '18 at 04:47
  • Hi @DilipTiwari please visit below link https://stackoverflow.com/questions/34206207/printing-the-view-in-ios-with-swift It will help you. – Maishi Wadhwani Aug 29 '18 at 06:46
  • this is my screen shot of what i m getting now :- https://imgur.com/a/X21ojN1 when i click on print button it presents print view but i m not getting image in print preview...and one more thing i m showing that image firstly from url and then i want to print @Maishi Sajnani – Dilip Tiwari Aug 29 '18 at 06:59
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178997/discussion-between-dilip-tiwari-and-maishi-sajnani). – Dilip Tiwari Aug 29 '18 at 07:34
  • Swift version worked for me thanks a lot @Maishi Sajnani for ur support – Dilip Tiwari Aug 29 '18 at 08:01
1

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];
    }
}
P.J
  • 6,547
  • 9
  • 44
  • 74
Sachin Siwal
  • 311
  • 1
  • 3
  • 13