Movatterモバイル変換


[0]ホーム

URL:


UIPrint​Interaction​Controller

Written byNate Cook
This article has been translated into:
中文

With all the different means to comment, mark up, save, and share right at our fingertips, it’s easy to overlook the value of a printed sheet of paper.

UIKit makes it easy to print straight from a user’s device with custom designs that you can adapt to both your content and the paper size. This article will first walk through how to format your content for printing, then detail the different ways to present (or not!) the printing interface.


The “printed” images throughout this article are taken from Apple’sPrinter Simulator. (The yellow edges represent the non-printable margins of the paper)

As of Xcode 6, the printer simulator must be downloaded as part of theHardware IO Tools for Xcode.

Download Hardware I/O Tools from Apple Developer Website

PrintSimulator App Info

PrintSimulator App Load Paper


At the heart of theUIKit Printing APIs isUIPrintInteractionController. A shared instance of this class manages details of print jobs and configure any UI that will be presented to the user. It also provides three levels of control for the formatting of your content.

Printing is a Job

Before we look at formatting actual content for printing, let’s go through the options for configuring the print job and the print options presented to the user.

UIPrintInfo

Print job details are set in aUIPrintInfo instance. You can use the following properties:

  • jobNameString: A name for this print job. The name will be displayed in the Print Center on the device and, for some printers, on the LCD display.
  • orientationUIPrintInfoOrientation: Either.Portrait (the default) or.Landscape—this is ignored if what you print has an intrinsic orientation, such as a PDF.
  • duplexUIPrintInfoDuplex:.None,.ShortEdge, or.LongEdge. The short- and long-edge settings indicate how double-sided pages could be bound, while.None suppresses double-sided printing (though not the UI toggle for duplexing, perplexingly).
  • outputTypeUIPrintInfoOutputType: Gives UIKit a hint about the type of content you’re printing. Can be any of:
    • .General (default): For mixed text and graphics; allows duplexing.
    • .Grayscale: Can be better than.General if your content includes black text only.
    • .Photo: For color or black and white images; disables duplexing and favors photo media for the paper type.
    • .PhotoGrayscale: Can be better than.Photo for grayscale-only images, depending on the printer.
  • printerIDString?: An ID for a particular printer—you can retrieve this onlyafter the user has selected a printer through the UI and save it to use as a preset for a future print job.

In addition,UIPrintInfo provides adictionaryRepresentation property, which can be saved and used to create a newUIPrintInfo instance later.

UIPrintInteractionController Settings

There are a handful of settings on theUIPrintInteractionController that you can configure before displaying the printing UI. These include:

  • printInfoUIPrintInfo: The aforementioned print job configuration.
  • printPaperUIPrintPaper: A simple type that describes the physical and printable size of a paper type; except for specialized applications, this will be handled for you by UIKit.
  • showsNumberOfCopiesBool: Whentrue, lets the user choose the number of copies.
  • showsPageRangeBool: Whentrue, lets the user choose a sub-range from the printed material. This only makes sense with multi-page content—it’s turned off by default for images.
  • showsPaperSelectionForLoadedPapersBool: When this istrue and the selected printer has multiple paper options, the UI will let the user choose which paper to print on.

Formatting Your Content

Through four different properties ofUIPrintInteractionController, you can select the level of control (and complexity) you want for your content.

  1. printingItemAnyObject! orprintingItems[AnyObject]!: At the most basic level, the controller simply takes content that is already printable (images and PDFs) and sends them to the printer.
  2. printFormatterUIPrintFormatter: At the next level, you can use aUIPrintFormatter subclass to format content inside your application, then hand the formatter off to theUIPrintInteractionController. You have some control over the format, and the printing API largely takes care of the rest.
  3. printPageRendererUIPrintPageRenderer: At the highest level, you can create a custom subclass ofUIPrintPageRenderer, combining page formatters and your own drawing routines for headers, footers, and page content.

Since Thanksgiving (my favorite holiday) is around the corner, to illustrate these properties we’ll add printing to different screens of a hypothetical app for Thanksgiving recipes.

Printing WithprintItem(s)

You can print pre-existing printable content by setting either theprintItem orprintItems property ofUIPrintInteractionController. Images and PDFs can be given either as image data (in aNSData,UIImage, orALAsset instance) or via anyNSURL referencing something that can be loaded into anNSData object. To be printable, images must be ina format thatUIImage supports.

Let’s walk through a very simple case: showing the UI to print an image when the user taps a button. (We’ll look at alternate ways of initiating printing below.) The process will be largely the same, no matter what you’re printing—configure your print info, set up the print interaction controller, and provide your content before displaying the UI:

@IBActionfuncprint(sender:UIBarButtonItem){ifUIPrintInteractionController.canPrintURL(imageURL){letprintInfo=UIPrintInfo(dictionary:nil)printInfo.jobName=imageURL.lastPathComponentprintInfo.outputType=.PhotoletprintController=UIPrintInteractionController.sharedPrintController()!printController.printInfo=printInfoprintController.showsNumberOfCopies=falseprintController.printingItem=imageURLprintController.presentAnimated(true,completionHandler:nil)}}

Easy as pie!(Or, in this case, sautéed Swiss chard.)

Print with .printingItem

ThepresentAnimated(:completionHandler:) method is for presenting the printing UI on theiPhone. If printing from theiPad, use one of thepresentFromBarButtonItem(:animated:completionHandler:) orpresentFromRect(:inView:animated:completionHandler:) methods instead.

UIPrintFormatter

TheUIPrintFormatter class has two subclasses that can be used to format text (UISimpleTextPrintFormatter andUIMarkupTextPrintFormatter) plus another (UIViewPrintFormatter) that can format the content of three views:UITextView,UIWebView, andMKMapView. Print formatters have a few properties that allow you to define the printed area of the page in different ways; the final print area for the formatter will be the smallest rectangle that meets the following criteria:

  • contentInsetsUIEdgeInsets: A set of insets from the edges of the page for the entire block of content. The left and right insets are applied on every page, but the top inset isonly applied on the first page. The bottom inset is ignored.
  • perPageContentInsetsUIEdgeInsets (iOS 8 only): A set of insets from the edges of the page forevery page of formatted content.
  • maximumContentWidth andmaximumContentHeightCGFloat: If specified, these can further constrain the width and height of the content area.

Though not clearly documented by Apple, all of these values are based on 72 points per inch.

The two text-based print formatters are initialized with the text they will be formatting.UISimpleTextPrintFormatter can handle plain or attributed text, whileUIMarkupTextPrintFormatter takes and renders HTML text in itsmarkupText property. Let’s try sending an HTML version of our Swiss chard recipe through the markup formatter:

letformatter=UIMarkupTextPrintFormatter(markupText:htmlString)formatter.contentInsets=UIEdgeInsets(top:72,left:72,bottom:72,right:72)// 1" marginsprintController.printFormatter=formatter

The result? A handsomely rendered HTML page:

Print with UIMarkupTextPrintFormatter

On the other hand, to use aUIViewPrintFormatter, you retrieve one from the view you want to print via itsviewPrintFormatter property. Here’s a look at how the formatter does its job for each of the three supported views:

1) UITextView

Print with UITextView

2) UIWebView

Print with UIWebView

3) MKMapView

Print with MKMapView

UIPrintPageRenderer

The built-in formatters are fine, but for themost control over the printed page, you can implement a subclass ofUIPrintPageRenderer. In your subclass you can combine the print formatters we saw above with your own custom drawing routines to create terrific layouts for your app’s content. Let’s look at one more way of printing a recipe, this time using a page renderer to add a header and to draw the images alongside the text of the recipe.

In the initializer, we save the data that we’ll need to print, then set theheaderHeight (the header and footer drawing methods won’t even be called unless you set their respective heights) and create a markup text formatter for the text of the recipe.

Complete Objective-C and Swift source code for the following examplesis available as a gist.

classRecipePrintPageRenderer:UIPrintPageRenderer{letauthorName:Stringletrecipe:Recipeinit(authorName:String,recipe:Recipe){self.authorName=authorNameself.recipe=recipesuper.init()self.headerHeight=0.5*POINTS_PER_INCHself.footerHeight=0.0// defaultletformatter=UIMarkupTextPrintFormatter(markupText:recipe.html)formatter.perPageContentInsets=UIEdgeInsets(top:POINTS_PER_INCH,left:POINTS_PER_INCH,bottom:POINTS_PER_INCH,right:POINTS_PER_INCH*3.5)addPrintFormatter(formatter,startingAtPageAtIndex:0)}}

When you use one or more print formatters as part of your custom renderer (as we’re doing here), UIKit queries them for the number of pages to print. If you’re doing truly custom page layout, implement thenumberOfPages() method to provide the correct value.

Next, we overridedrawHeaderForPageAtIndex(:inRect:) to draw our custom header. Unfortunately, those handy per-page content insets on print formatters are gone here, so we first need to inset theheaderRect parameter to match my margins, then simply draw into the current graphics context. There’s a similardrawFooterForPageAtIndex(:inRect:) method for drawing the footer.

overridefuncdrawHeaderForPageAtIndex(pageIndex:Int,varinRectheaderRect:CGRect){varheaderInsets=UIEdgeInsets(top:CGRectGetMinY(headerRect),left:POINTS_PER_INCH,bottom:CGRectGetMaxY(paperRect)-CGRectGetMaxY(headerRect),right:POINTS_PER_INCH)headerRect=UIEdgeInsetsInsetRect(paperRect,headerInsets)// author name on leftauthorName.drawAtPointInRect(headerRect,withAttributes:nameAttributes,andAlignment:.LeftCenter)// page number on rightletpageNumberString:NSString="\(pageIndex+1)"pageNumberString.drawAtPointInRect(headerRect,withAttributes:pageNumberAttributes,andAlignment:.RightCenter)}

Lastly, let’s provide an implementation ofdrawContentForPageAtIndex(:inRect:):

overridefuncdrawContentForPageAtIndex(pageIndex:Int,inRectcontentRect:CGRect){ifpageIndex==0{// only use rightmost two inches of contentRectletimagesRectWidth=POINTS_PER_INCH*2letimagesRectHeight=paperRect.height-POINTS_PER_INCH-(CGRectGetMaxY(paperRect)-CGRectGetMaxY(contentRect))letimagesRect=CGRect(x:CGRectGetMaxX(paperRect)-imagesRectWidth-POINTS_PER_INCH,y:paperRect.origin.y+POINTS_PER_INCH,width:imagesRectWidth,height:imagesRectHeight)drawImages(recipe.images,inRect:imagesRect)}}

With the implementation of our custom page renderer complete, we can set an instance as thepageRenderer property on the print interaction controller and we’re ready to print.

letrenderer=RecipePrintPageRenderer(authorName:"Nate Cook",recipe:selectedRecipe)printController.printPageRenderer=renderer

The final result is much nicer than any of the built-in formatters.

Note that the text of the recipe is being formatted by aUIMarkupTextPrintFormatter, while the header and images are drawn via custom code.

Print with UIPrintPageRenderer subclass

Printing via a Share Sheet

With the tools we’ve learned above, adding printing capability in a share sheet is simple. Instead of usingUIPrintInteractionController to present the printing UI, we pass off our configuredUIPrintInfo and printing item(s), formatter, or renderer to aUIActivityViewController. If the user selects thePrint button in the share sheet, the printing UI will be displayed with all our configurations intact.

@IBActionfuncopenShareSheet(){letprintInfo=...letformatter=...letactivityItems=[printInfo,formatter,textView.attributedText]letactivityController=UIActivityViewController(activityItems:activityItems,applicationActivities:nil)presentViewController(activityController,animated:true,completion:nil)}

WhileUIPrintInfo and subclasses ofUIPrintFormatter andUIPrintPageRenderer can be passed to aUIActivityViewController as activities, none of them seem to conform to theUIActivityItemSource protocol, so you’ll see a (harmless) warning in your console about “Unknown activity items.”

Skipping the Printing UI

New in iOS 8 is a way to print without any presentation of the printing UI. Instead of presenting the UI each time the user presses a print button, you can provide a way for your users to select a printer somewhere in your app with the easy-to-useUIPrinterPickerController. It accepts an optionalUIPrinter instance in its constructor for a pre-selection, uses the same presentation options as explained above, and has a completion handler for when the user has selected her printer:

letprinterPicker=UIPrinterPickerController(initiallySelectedPrinter:savedPrinter)printerPicker.presentAnimated(true){(printerPicker,userDidSelect,error)inifuserDidSelect{self.savedPrinter=printerPicker.selectedPrinter}}

Now you can tell yourUIPrintInteractionController to print directly by callingprintToPrinter(:completionHandler:) with the saved printer instead of using one of thepresent... methods.


As one final recommendation, consider the printed page as you would any other way of interacting with your content. In the same way you scrutinize font size and weight or the contrast between elements on screen, make sure to test your print layoutson paper—the contrast, size, and margins should all be appropriate to the medium.

NSMutableHipster

Questions? Corrections?Issues andpull requests are always welcome.

This article uses Swift version 1.0. Find status information for all articles on thestatus page.

Written byNate Cook
Nate Cook

Nate Cook (@nnnnnnnn) is an independent web and application developer whowrites frequently about topics in Swift, and the creator ofSwiftDoc.org.

Next Article

After taking a look at WatchKit, there were a few things that jumped out coming from UIKit. They’re the kind of subjective, opinionated things that don’t make for good documentation, but might be interesting or useful to anyone else as they’re getting started.


[8]ページ先頭

©2009-2025 Movatter.jp