我有一个在 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()
}
}
最佳答案
抱歉,这完全是我的误解。完全错误的原因。我可以给文件加水印,然后我可以保存它或打印它,水印就会出现。我不需要单独的保存功能。 Ou man 我让我的头很好,有时你坐在软管上。非常感谢您的大力帮助。
关于swift - 如何在 PDF 文件上保存水印并导出到桌面 macOS Mojave,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415176/