The UIWebView class provides a lot of useful functions to manage complex documents, html, .doc, .pdf etc etc
In this article we will see how to print its content.
webView is the UIWebView I want to print.
- Show the printing user interface.
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
- Prepare a print-information object initialized with default values.
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
- Set the output type.
printInfo.outputType = UIPrintInfoOutputGeneral;
pic.printInfo = printInfo;
the output type could assume the following values:
UIPrintInfoOutputGeneral Text, Graphics and images.
UIPrintInfoOutputPhoto Black and white or color images
UIPrintInfoOutputGrayscale content is in gray scale.
- Lay out the drawn content of the view for printing.
pic.printFormatter = [webView viewPrintFormatter];
- Show the page range
pic.showsPageRange = YES;
- Wait for completion
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *printController, BOOL completed, NSError *error)
{
if (!completed && error)
{
NSLog(@"Printing could not complete because of error: %@", error);
}
};
[pic presentAnimated:YES completionHandler:completionHandler];
That's all, it's easy and fast. You can try this code also on simulator using the Printer Simulator.
If you found useful this article, please share it using the social buttons below. Thank you in advance.
Gg1
I really like the tutorial! I got everything to work great, but I am making a universal app and I was wondering if you could tell me how to make your code work on the iPad as well? Thanks for a wonderful tutorial!
I'm mostly getting good result from the method described here, but am concerned about warning messages rec'd on the console. One says "WARNING: Calling – [UIPintInteractionController presentAnimated:completionHandler:] on iPad. The next one says: -[UIPopoverController presentPopoverFromRect:inView:permittedArrowDirections:animated:]: the rect passed in to this method must have non-zero width and height. This will be an exception in a future release.
Here is the code I'm using to invoke the pic:
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
pic.printInfo = printInfo;
pic.printFormatter = [myWebPage viewPrintFormatter];
[pic presentAnimated:NO completionHandler:completionHandler];
Good tutorial. Simple and to the point. Thanks for posting.
Any idea how to get AirPrint to honor the web page's "@media print" directives in its CSS? When printed from a Mac or PC, the @media print CSS directives format the printed output differently (no nav bars, no background, etc.)