У меня есть приложение, работающее в MacOS Mojave, и оно прекрасно работает.Я могу перетащить файл PDF в PDFView и поставить кнопку, чтобы пометить водяной знак в файле PDF.Я получил пример кода от Apple WWDC, написанный для iOS, и перевел его для macOS.Моя проблема в том, как я могу сохранить этот PDF-файл, включая водяные знаки, на рабочем столе, например?
Мой код:
override func viewDidLoad() {
super.viewDidLoad()
pdfView?.acceptsDraggedFiles = true
}
func classForPage() -> AnyClass {
return WatermarkPage.self
}
@IBAction func WaterMark(_ sender: NSButton) {
if let document = PDFDocument(url: (pdfView?.document?.documentURL)!){
//Center document on gray background
pdfView?.autoScales = true
pdfView?.backgroundColor = NSColor.lightGray
// 1. Set delegate
document!.delegate = self
pdfView?.document = document
let filename: String = "ExportPDF.pdf"
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,
true)[0];
let writePath = URL(fileURLWithPath: path).appendingPathComponent(filename).path
//pdfView?.document?.write(toFile: writePath)
document?.write(toFile: writePath)
print("Pfad: \(path)")
}
}
class WatermarkPage: PDFPage {
// 3. Override PDFPage custom draw
/// - Tag: OverrideDraw
override func draw(with box: PDFDisplayBox, to context: CGContext) {
// Draw original content
super.draw(with: box, to: context)
// Draw rotated overlay string
context.saveGState()
let pageBounds = self.bounds(for: box)
context.translateBy(x: 0.0, y: pageBounds.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.rotate(by: CGFloat.pi / 5.0)
let string: NSString = "A P P R O V E D"
let attributes = [NSAttributedString.Key.foregroundColor: NSColor(calibratedRed: 0.8, green: 0.5, blue: 0.5, alpha: 0.5),NSAttributedString.Key.font: NSFont.boldSystemFont(ofSize: 64.0)]
string.draw(at: CGPoint(x: 300, y: 40), withAttributes: attributes)
context.restoreGState()
context.saveGState()
}
}