PDFに画像を挿入してPDFを編集し、挿入された画像で新しいPDFを保存するクラスがあります。
以下のコードは、カスタムを作成することにより、シナリオを達成するために使用する方法ですPDFAnnotation
。対角線上に黒い線が描かれないようにするため、.widget
代わりにtype を指定します。.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ファイルに画像を表示するにはどうすればよいですか?
ありがとう。