Split PDFs in iOS

PSPDFKit’s Processor API enables you to split a PDF document into multiple documents.

Processor can extract ranges of pages from one document and put them into another document. If you run this operation multiple times with different page indexes, you can effectively split a PDF into as many documents as you require.

In most cases, you’ll want to use Processor to create PDF documents on disk based on a current Document. This example code will split a single PDF document into two at the provided page index:

let document = ...

// Split on the fifth page.
let splitIndex = 5
precondition(splitIndex > 0 && splitIndex < document.pageCount)

// Save the output in the app documents directory.
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let splitPath = documentsDirectory.appendingPathComponent("Split")

let ranges = [IndexSet(integersIn: 0...splitIndex - 1),
              IndexSet(integersIn: splitIndex...Int(document.pageCount - 1))]

for (index, indexSet) in ranges.enumerated() {
    let configuration = Processor.Configuration(document: document)!
    // Specify the page range to keep after processing.
    configuration.includeOnlyIndexes(indexSet)

    let processor = Processor(configuration: configuration, securityOptions: nil)
    // Save to a new file on disk. Use a unique name.
    let output = URL(string: "\(splitPath)_\(index)_\(NSUUID().uuidString).pdf")!
    try processor.write(toFileURL: output)
}

Similar functionality is also available via the Document Editor. Please see the PDFDocumentEditor.exportPages(_,to:, withCompletionBlock:) API documentation for more information.