Skip to Content
NexPDF

Getting started

Activate a license, open a PDF, count its pages, render a page to PNG and extract its text with NexPDF for iOS (Swift).

English

This example opens a bundled PDF, prints the page count, renders the first page to a UIImage and prints the text of every page. It runs without a license key too: viewing is always allowed, and rendered pages then carry a watermark.

Add the package

Add https://github.com/nexdevit/nexpdf-swift with the NexPdf product, as described in Installation. Add sample.pdf and, if you have one, nexpdf_license.xml to the app target.

Write the code

Quickstart.swift
import NexPdf
import UIKit

func quickstart() throws -> UIImage? {
    // 1. Activate the license once per launch (optional for viewing).
    if let url = Bundle.main.url(forResource: "nexpdf_license", withExtension: "xml") {
        let key = try String(contentsOf: url, encoding: .utf8)
        _ = try NexPdf.activateLicense(key)                 // app id = bundle id
    }

    // 2. Open the document.
    let url = Bundle.main.url(forResource: "sample", withExtension: "pdf")!
    let doc = try NexPdfDocument.open(url: url)

    // 3. Page count and size.
    let size = doc.pageSize(0)
    print("\(doc.pages) pages, first page \(Int(size.width)) x \(Int(size.height)) pt")

    // 4. Render the first page at 144 dpi.
    let png = try doc.renderPagePng(pageIndex: 0, dpi: 144)

    // 5. Extract the text of every page.
    for i in 0..<doc.pages {
        print("--- page \(i + 1) ---")
        print(try doc.extractPageText(pageIndex: i))
    }
    return UIImage(data: png)
}

Run it

Call quickstart() from a view or view controller and show the image, for example in an Image(uiImage:). Errors are thrown as NexPdfError.

What the code does

  • NexPdf.activateLicense(_:appId:platform:) accepts the license XML or the bare key. The app id defaults to the bundle id and the platform to ios (macos on macOS). See License.
  • NexPdfDocument.open(url:password:) and open(data:password:) open a PDF. Word, Excel and PowerPoint files are converted when the license includes conversion.
  • pageSize(_:) is the displayed size in points as a CGSize: crop box, rotation and /UserUnit applied.
  • renderPagePng(pageIndex:dpi:) returns PNG Data. 72 dpi is one pixel per point.
  • extractPageText(pageIndex:) returns the page text in reading order.
  • write(to:) saves the document to a file, and saveBytes() returns it as Data.

Next steps

On this page