Search code examples
iosswiftpdfdrawpdfkit

How to draw a signature or add an image signature to a PDF in Swift


By using below code I'm able to load the pdf. Then I have added an add signature button at navigation bar. On click of the add signature button should allow me to browse the signature image then after click the add button it should add the signature on the pdf and back to first view controller.

or in the first view controller when the pdf is displaying how to draw a signature

import UIKit 
import PDFKit

class ViewController: UIViewController { @IBOutlet weak var pdfContainerView: PDFView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "PDF Viewer"
    setupPdfView()
}

func setupPdfView() {
  
    if let path = Bundle.main.path(forResource: "sample", ofType: "pdf") {
        if let pdfDocument = PDFDocument(url: URL(fileURLWithPath: path)) {
            pdfContainerView.displayMode = .singlePageContinuous
            pdfContainerView.autoScales = true
            pdfContainerView.displayDirection = .vertical
            pdfContainerView.document = pdfDocument
        }
    }
}
}

enter image description here


Solution

  • add file ImageStampAnnotation.swift

    class ImageStampAnnotation: PDFAnnotation {
    var image: UIImage!
    
    init(with image: UIImage!, forBounds bounds: CGRect, withProperties properties: [AnyHashable : Any]?) {
        super.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp,  withProperties: properties)
        self.image = image
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(with box: PDFDisplayBox, in context: CGContext)   {
        guard let cgImage = self.image.cgImage else { return }
        context.draw(cgImage, in: self.bounds)
    }
    }
    

    set Annotation in current page of pdf

    func setupPdfView() {
        
        if let path = Bundle.main.path(forResource: "sample", ofType: "pdf") {
            if let pdfDocument = PDFDocument(url: URL(fileURLWithPath: path)) {
                pdfContainerView.displayMode = .singlePageContinuous
                pdfContainerView.autoScales = true
                pdfContainerView.displayDirection = .vertical
                pdfContainerView.document = pdfDocument
                
                // position of sign image
                let rect = CGRect(x: 10, y: 10, width: 200, height: 35)
                let imageAnnotation = ImageStampAnnotation(with: UIImage(named: "signer"), forBounds: rect, withProperties: nil)
                pdfContainerView.currentPage?.addAnnotation(imageAnnotation)
            }
        }
    }