ios - Swift 4 你能用图像注释 PDF 吗

标签 ios swift pdf

我是 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 而不是绘制函数,但这会给出错误“无法将类型‘UIImage’的值分配给类型‘String?’”

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

如有任何帮助,我们将不胜感激!!

最佳答案

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

创建自定义 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)

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

关于ios - Swift 4 你能用图像注释 PDF 吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49192045/

相关文章:

Python - 如何将 BMP 转换为 JPEG 或 PDF?这样文件大小就不是 50MB 而是更小了?

ios - 尽管有背景音频功能和 session 类别,背景音频仍停止

ios - UIImageView 和 UIButton 背景图像在模拟器中加载时变黑

swift - TableView 中的 SDWebImage 向上滚动

javascript - HTML5 Canvas ,使用 jspdf.js 将 Canvas 转换为 PDF

pdf - iframe 无法将 jsPDF 输出识别为 pdf 格式

IOS:WebView中VoiceOver改成英文

objective-c - 每个按钮都有不同 View 的 UITableView

iphone - 如何在 NSMutableUrlRequest 中发布文本和图像数据?

ios - 如何通过按钮重新获得互联网后重新加载tableView