Swift 4您可以使用图像注释PDF吗? [英] Swift 4 Can you annotate a PDF with an image
问题描述
我对Swift编程很新,我已经创建了一个应用程序,用于简化任务,我以编程方式填写现有PDF上的字段。我已经将签名捕获为UIImage,我想将其作为注释添加到PDF中,就像其他字段一样。这可能吗?
I'm fairly new to Swift programming and I've created an app for work to simplify a task where I programmatically fill-in fields on an existing PDF. I've captured a signature as a UIImage and I'd like to add this to the PDF as an annotation like the rest of the fields. Is this possible?
// 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而不是绘制函数但这会给出错误'无法分配类型'UIImage的值'来键入'String?''
I've also tried: signatureField.stampName = sigImage as! UIImage instead of the draw function but this gives the error 'Cannot assign value of type 'UIImage' to type 'String?''
屏幕截图显示了我注释的内容:
The screenshot shows what I get annotated:
任何帮助都可以非常感谢!!
Any help at all would be greatly appreciated!!
推荐答案
这对我来说也很棘手,但我想出来了。
This was tricky for me too, but I figured it out.
创建自定义PDFAnnotation,然后覆盖draw方法以在pdf上下文中绘制图像。
Create a custom PDFAnnotation, then override the draw method to draw the image in the pdf context.
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)
}
}
然后,只需将其添加到文档中
Then, just add it to the document
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
I wrote a medium article on how I did it, added a gesture recognizer to it and a canvas to grab a signature: https://medium.com/@rajejones/add-a-signature-to-pdf-using-pdfkit-with-swift-7f13f7faad3e
这篇关于Swift 4您可以使用图像注释PDF吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!