Merge Multiple Images into One PDF on iOS Using Swift

An iOS app written in Swift can pick multiple photos from the gallery, optionally auto-crop documents with Dynamsoft Document Normalizer, and merge the results into a single multi-page PDF. This is useful for ID cards, receipts, or any workflow that needs several images combined into one shareable document.

What you’ll build: An iOS app in Swift that picks multiple photos from the gallery, optionally auto-crops each one with Dynamsoft Document Normalizer, and writes the normalized pages into one PDF with PDFKit before handing it to the iOS share sheet.

Key Takeaways

  • CaptureVisionRouter detects the document boundary and normalizes each photo in a single call; the normalized pages are read from processedDocumentResult.deskewedImageResultItems.
  • PHPickerViewController allows unlimited multi-image selection without requiring full photo library permission on iOS.
  • The SDK supports binary (black & white), grayscale, and color output modes — binary mode reduces file size significantly and cleans noisy backgrounds.
  • PDFKit assembles the normalized pages into one multi-page PDF. ImageIO.saveToFile overwrites its target file instead of appending, so calling it once per page leaves only the last page in the file.
  • This approach is ideal for ID card scanning, receipt archiving, and any workflow that combines camera-roll images into one shareable PDF.

Common Developer Questions

How do I merge multiple UIImages into one PDF file on iOS using Swift?

Pick multiple images with PHPickerViewController, normalize each one with CaptureVisionRouter, and insert every deskewed page into a single PDFDocument before writing the file. That is the end-to-end merge path implemented in this Swift sample.

How can I auto-crop a document from a photo and save it as a PDF on iPhone?

Enable the auto-cropping option, run each selected photo through CaptureVisionRouter to detect the document boundaries, and then use the normalized output rather than the original full image when building the PDF. That gives you flatter pages and a cleaner final document.

What is the best Swift SDK for converting scanned images to PDF with edge detection?

Dynamsoft Document Normalizer is the SDK used in this tutorial because it combines document-boundary detection, perspective correction, and color-mode control in one iOS API, while PDFKit supplies the multi-page PDF container. That makes it a stronger fit than stitching together a separate edge-detection library and a PDF writer by hand.

Prerequisites

  • Xcode 16 or later
  • iOS 15+ deployment target (PHPickerViewController requires iOS 14; the sample targets iOS 15)
  • CocoaPods installed (gem install cocoapods)
  • Get a 30-day free trial license for Dynamsoft Document Normalizer

Step 1: Create a New Xcode Project

Open Xcode and create a new app project.

Step 2: Add Dynamsoft SDK Dependencies via CocoaPods

Next, add Dynamsoft Capture Vision — the bundle that contains Document Normalizer — via CocoaPods.

  1. Init a pod project.

    pod init
    
  2. Add the following to Podfile. Dynamsoft Capture Vision 3.x ships the router, document normalizer, image processing, utility, and license modules in a single pod, so the six 2.x pods collapse into one dependency.

    platform :ios, '15.0'
    
    target 'PDFCreator' do
      use_frameworks!
      pod 'DynamsoftCaptureVisionBundle','3.6.4000'
    end
    
  3. Install the pods.

    pod install
    

Step 3: Design the Image Selection and PDF Settings UI

Open Main.storyboard and add the following controls:

screenshot

It contains a button to select images from the gallery, a switch to enable auto cropping of the document in the image and a picker view to select which color mode to use for the images in the PDF.

The picker view is configured with the following code:

@IBOutlet weak var colorModeUIPickerView: UIPickerView!
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
   
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return 3
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
                    forComponent component: Int) -> String? {
    if row == 0 {
        return "Black & White"
    }else if row == 1 {
        return "Grayscale"
    }else{
        return "Color"
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    colorModeUIPickerView.dataSource = self
    colorModeUIPickerView.delegate = self
}

Here, we use PHPickerViewController to pick multiple images.

@IBAction func selectImagesUIButton_clicked(_ sender: Any) {

    var configuration = PHPickerConfiguration(photoLibrary: .shared())
    //0 - unlimited 1 - default
    configuration.selectionLimit = 0
    configuration.filter = .images
    let pickerViewController = PHPickerViewController(configuration: configuration)
    pickerViewController.delegate = self
    present(pickerViewController, animated: true)
}

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    print(results.count)
    picker.dismiss(animated: true)
}

We can convert the results into an array of UIImage for further use.

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    picker.dismiss(animated: true)
    DispatchQueue.main.async {
        var images: [UIImage] = []
        var processed = 0
        let size = results.count
        for item in results {
            if item.itemProvider.canLoadObject(ofClass: UIImage.self) {
                item.itemProvider.loadObject(ofClass: UIImage.self) { image, error in
                    if let error {
                        NSLog("Failed to load the picked image: %@", error.localizedDescription)
                    }
                    if let selectedImage = image as? UIImage {
                        images.append(selectedImage)
                        processed = processed + 1
                        if processed == size {
                            self.mergeImagesIntoPDF(images: images)
                        }
                    }
                }
            }
        }
    }
}

Step 5: Merge Images into a PDF with Document Normalization

  1. Initialize the license for Dynamsoft Document Normalizer in AppDelegate.swift.

    import DynamsoftCaptureVisionBundle
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let oneDayTrial = "LICENSE-KEY"
        LicenseManager.initLicense(oneDayTrial, verificationDelegate: self)
        return true
    }
    func onLicenseVerified(_ isSuccess: Bool, error: (any Error)?) {
        if isSuccess == false {
            print("license invalid")
        }else{
            print("license valid")
        }
    }
    
  2. Create an instance of Capture Vision Router to call Dynamsoft Document Normalizer.

    import DynamsoftCaptureVisionBundle
    
    let cvr: CaptureVisionRouter = CaptureVisionRouter()
    
  3. Normalize each image and merge the pages into one PDF. CaptureVisionRouter returns the deskewed page for every photo, and PDFKit appends one page per image before the file is shared to Files.

    If enableAutoCroppingUISwitch is on, the DetectAndNormalizeDocument_Default template detects the document boundary and crops the page. Otherwise the NormalizeDocument_Default template normalizes the whole image, with the ROI set to the full frame.

    The color mode is applied through documentSettings.colourMode. Converting an image to black and white cleans the background and reduces the file size, while grayscale keeps more detail at a moderate size.

    import DynamsoftCaptureVisionBundle
    import PDFKit
    
    func mergeImagesIntoPDF(images: [UIImage]) {
        var enableAutoCropping = false
        var selectedColorModeIndex = 0
        DispatchQueue.main.sync {
            statusLabel.text = "Processing..."
            enableAutoCropping = enableAutoCroppingUISwitch.isOn
            selectedColorModeIndex = colorModeUIPickerView.selectedRow(inComponent: 0)
        }
    
        let templateName = enableAutoCropping
            ? PresetTemplate.detectAndNormalizeDocument.rawValue
            : PresetTemplate.normalizeDocument.rawValue
    
        guard let settings = try? cvr.getSimplifiedSettings(templateName) else {
            statusLabel.text = ""
            return
        }
    
        switch selectedColorModeIndex {
        case 0:
            settings.documentSettings?.colourMode = ImageColourMode.binary
        case 1:
            settings.documentSettings?.colourMode = ImageColourMode.grayscale
        default:
            settings.documentSettings?.colourMode = ImageColourMode.colour
        }
    
        if !enableAutoCropping {
            // Normalize the whole image when document detection is off.
            let fullPage = [CGPoint(x: 0, y: 0), CGPoint(x: 100, y: 0), CGPoint(x: 100, y: 100), CGPoint(x: 0, y: 100)]
            settings.roi = Quadrilateral(pointArray: fullPage.map { NSValue(cgPoint: $0) })
            settings.roiMeasuredInPercentage = true
        }
        try? cvr.updateSettings(templateName, settings: settings)
    
        let pdfDocument = PDFDocument()
        for image in images {
            let capturedResult = cvr.captureFromImage(image, templateName: templateName)
            let deskewedItems = capturedResult.processedDocumentResult?.deskewedImageResultItems ?? []
            for item in deskewedItems {
                if let imageData = item.imageData,
                   let pageImage = try? imageData.toUIImage(),
                   let page = PDFPage(image: pageImage) {
                    pdfDocument.insert(page, at: pdfDocument.pageCount)
                }
            }
        }
    
        let url = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
            .appendingPathExtension("pdf")
        pdfDocument.write(to: url)
    
        DispatchQueue.main.async {
            self.statusLabel.text = ""
            let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            self.present(activityVC, animated: true)
        }
    }
    

Two 3.x API details shape this code. Quadrilateral(pointArray:) takes [NSValue], so every CGPoint is wrapped with NSValue(cgPoint:), and the normalized page arrives as a DeskewedImageResultItem instead of the 2.x NormalizedImageResultItem.

Do not call ImageIO.saveToFile once per page with the same path: that API overwrites the file, so a loop leaves a single-page PDF containing only the last image.

Screenshot of converted files:

diagram

Common Issues and Edge Cases

  • Large images cause memory pressure: If users select many high-resolution photos, the app may run out of memory. Consider down-sampling UIImage instances before passing them to CaptureVisionRouter.
  • Auto-crop fails on plain backgrounds: The document boundary detection works best when there is contrast between the document and the surface. On a white document against a white desk, disable auto-cropping or guide users to use a darker background.
  • PDF file not appearing in share sheet: Ensure the temporary file URL has the .pdf extension. UIActivityViewController uses the file extension to determine available share targets.
  • Only the last selected image ends up in the PDF: ImageIO.saveToFile and the removed ImageManager.saveToFile overwrite the target file. Keep one PDFDocument and insert a PDFPage per normalized image, as the sample does.
  • Quadrilateral initializer mismatch: the initializer expects [NSValue] in 3.x. Passing [CGPoint] directly fails to compile; map the points with NSValue(cgPoint:) first.

Source Code

Get the complete sample project source code on GitHub