如何在 Swift 中绘制签名或将图像签名添加到 PDF

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

通过使用下面的代码,我可以加载 pdf。然后我在导航栏上添加了一个添加签名按钮。单击添加签名按钮应该允许我浏览签名图像,然后在单击添加按钮后它应该在 pdf 上添加签名并返回到第一个视图控制器。

或者当 pdf 显示如何绘制签名时在第一个视图控制器中

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
        }
    }
}
}

添加文件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)
}
}

在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)
        }
    }
}

您可以使用 Apple 的内置 pdf 预览和内置注释,其中还包括用户的签名。 如何实现 QLPreviewViewController 在 post 中有说明: