【问题标题】:Swift 4 Can you annotate a PDF with an imageSwift 4 你可以用图像注释 PDF
【发布时间】:2018-03-09 10:49:04
【问题描述】:

我是 Swift 编程的新手,我创建了一个工作应用程序来简化我以编程方式在现有 PDF 上填写字段的任务。我已将签名捕获为 UIImage,我想将其作为注释添加到 PDF 中,就像其他字段一样。这可能吗?

// Annotate Signature
let signatureFieldBounds = CGRect(x:390, y:142, width:100, height:30)
let signatureField = PDFAnnotation(bounds: signatureFieldBounds, forType: .stamp, withProperties: nil)
signatureField.fieldName = FieldNames.signature.rawValue
signatureField.backgroundColor = UIColor.clear
sigImage?.draw(in: signatureFieldBounds)

page.addAnnotation(signatureField)

我也试过:signatureField.stampName = sigImage as! UIImage 而不是 draw 函数,但这会给出错误“无法将类型 'UIImage' 的值分配给类型 'String?'”

屏幕截图显示了我得到注释的内容:

任何帮助将不胜感激!

【问题讨论】:

  • 错误意味着 signatureField.stampName 需要 String 而不是 UIImage
  • 谢谢,我理解错误,如果可能的话,我想弄清楚如何放置图像。
  • 你检查过this吗?

标签: ios swift pdf


【解决方案1】:

这对我来说也很棘手,但我想通了。

创建自定义 PDFAnnotation,然后重写 draw 方法以在 pdf 上下文中绘制图像。

class ImageStampAnnotation: PDFAnnotation {

var image: UIImage!

// A custom init that sets the type to Stamp on default and assigns our Image variable
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) {

    // Get the CGImage of our image
    guard let cgImage = self.image.cgImage else { return }

    // Draw our CGImage in the context of our PDFAnnotation bounds
    context.draw(cgImage, in: self.bounds)

 } 
}

然后,只需将其添加到文档中

guard let signatureImage = signatureImage, let page = pdfContainerView.currentPage else { return }
    let pageBounds = page.bounds(for: .cropBox)
    let imageBounds = CGRect(x: pageBounds.midX, y: pageBounds.midY, width: 200, height: 100)
    let imageStamp = ImageStampAnnotation(with: signatureImage, forBounds: imageBounds, withProperties: nil)
    page.addAnnotation(imageStamp)

我写了一篇关于我是如何做到这一点的中型文章,向其中添加了一个手势识别器和一个用于获取签名的画布: https://medium.com/@rajejones/add-a-signature-to-pdf-using-pdfkit-with-swift-7f13f7faad3e

【讨论】:

  • 非常感谢 Rajee!这正是我所需要的,它工作得很好!我使用“Stamp”子类型进行了一半,但在设置上下文时遇到了麻烦。再次感谢您,非常感谢!
  • 不工作无法绘制签名。你能检查一下吗? @Rajee
  • 不工作,我试图通过创建图像的 cgpoints 传递,但我把它颠倒了
猜你喜欢
  • 1970-01-01
  • 2014-10-27
  • 2014-07-22
  • 2020-05-26
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多