首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift 4你能用图片注释PDF吗?

Swift 4你能用图片注释PDF吗?
EN

Stack Overflow用户
提问于 2018-03-09 18:49:04
回答 1查看 3.4K关注 0票数 2

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

代码语言:javascript
复制
// 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?‘”

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

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2018-03-17 03:45:42

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

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

代码语言:javascript
复制
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)

 } 
}

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

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49192045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档