如何在PDF文件上保存水印并导出到桌面macOS Mojave

时间:2018-11-21 15:18:17

标签: swift cocoa pdf

我有一个在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()

    }
}

2 个答案:

答案 0 :(得分:0)

对不起,这完全是我的误解。完全错误原因。我可以给文档加水印,然后我可以保存或打印文档,水印就会出现。我不需要单独的保存功能。哦,我有时会把我的头弄得很好,你坐在水带上。非常感谢您的大力帮助。

答案 1 :(得分:-1)

如果要将其保存到桌面。

您必须更改文件写入的路径

例如标准的Desktop / Users / username / Desktop /

let fileManager = FileManager.default
let homeURL =  FileManager.default.urls(for: NSHomeDirectory, in: .userDomainMask).first! as NSURL
let writePath = homeURL.path + "Desktop" + <Filename>

document?.write(toFile: writePath)