Airprint iOS Tutorial

With Airprint-enabled printers it is possible to print wireless from an iPhone or an iPad. In this tutorial the text within a Text View will be printed. This tutorial is made with Xcode 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11AirPrintTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

To test the AirPrint ability we need to install the Printer Simulator. Go to developer.apple.com/downloads and download Additional Tools for Xcode 9.

Open the Printer Simulator. The Simulator has some virtual printers included which we can use in our application.

Go to the Storyboard and drag a Text View to the main view. Also drag a button to the main view and place it below the Text View. Set the button's title to Print.

Select the Text View and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Text View and select the Auto Layout pin button. Pin the Button to the top and and click "Add 1 Constraint".

Select the button and Ctrl and drag to the Text View and select the Vertical Spacing option.

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Thr Text View to the ViewController class and create the following Outlet

Ctrl and drag from the Button to the ViewController class and create the following Action.

 

Implement the printText method

 @IBAction func printText(_ sender: Any) {
    // 1
    let printController = UIPrintInteractionController.shared
    // 2
    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.outputType = UIPrintInfoOutputType.general
    printInfo.jobName = "print Job"
    printController.printInfo = printInfo
            
    // 3
    let formatter = UIMarkupTextPrintFormatter(markupText: textView.text)
    formatter.perPageContentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
    printController.printFormatter = formatter
            
    // 4
   printController.present(animated: true, completionHandler: nil)
}
  1. The UIPrintInteractionController presents the user interface and manages the printing.
  2. The UIPrintinfo object contains information about the print job, This information is assigned to the printInfo property of the UIPrintInteractionController.
  3. The printing text can be formatted. here we define the insets for the printing page
  4. The user is presented the iPhone printing interface to select a printer and the number of copies

Build and Run the project.

You can download the source code of the IOS11AirPrintTutorial at the ioscreator repository on Github.