我有一个类可以通过将图像插入 pdf 并使用插入的图像保存新的 pdf 来编辑 pdf。
下面的代码是我用来实现场景的方式,通过创建自定义PDFAnnotation
. 我将 type 指定为,.widget
而不是.stamp
避免在对角线上绘制黑线。
final private class PDFImageAnnotation: PDFAnnotation {
var image: UIImage?
convenience init(_ image: UIImage?, bounds: CGRect, properties: [AnyHashable: Any]?) {
self.init(bounds: bounds, forType: PDFAnnotationSubtype.widget, withProperties: properties)
self.image = image
}
override func draw(with box: PDFDisplayBox, in context: CGContext) {
super.draw(with: box, in: context)
// Drawing the image within the annotation's bounds.
guard let cgImage = image?.cgImage else { return }
context.draw(cgImage, in: bounds)
}
}
以下是我如何显示 pdf 并选择要保存为 pdf 的图像
private func setupPDF() {
guard let url = url else { return }
pdfView.document = PDFDocument(url: url)
pdfView.autoScales = true
}
private func addImageAndSave(_ image: UIImage) {
guard let page = pdfView.currentPage else { return }
let pageBounds = page.bounds(for: .cropBox)
let imageBounds = CGRect(x: pageBounds.midX, y: pageBounds.midY, width: image.size.width, height: image.size.height)
let imageStamp = PDFImageAnnotation(image, bounds: imageBounds, properties: nil)
imageStamp.shouldDisplay = true
imageStamp.shouldPrint = true
page.addAnnotation(imageStamp)
// Save PDF with image
let fileName = url.lastPathComponent
let saveUrl = FileManager.default.temporaryDirectory.appendingPathComponent(fileName, isDirectory: false)
pdfView.document?.write(to: saveUrl)
}
但是结果pdf文件如下
右栏中的预览确实显示了图片,但是当在Preview
应用程序或任何浏览器中打开 pdf 时,图片不存在。
如何使图片出现在最终的 pdf 文件中?
谢谢。