How can I save a watermark on PDF File and export to Desktop macOS Mojave












1















I have an app running in macOS Mojave and it works nicely. I can drag a pdf file onto a PDFView and can put a button to mark a watermark on the pdf file. I got the example code from apple WWDC written for iOS, and I translated it for macOS. My problem is how can I save this pdf including the watermark, to desktop for example?





My Code:



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()

}
}









share|improve this question





























    1















    I have an app running in macOS Mojave and it works nicely. I can drag a pdf file onto a PDFView and can put a button to mark a watermark on the pdf file. I got the example code from apple WWDC written for iOS, and I translated it for macOS. My problem is how can I save this pdf including the watermark, to desktop for example?





    My Code:



    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()

    }
    }









    share|improve this question



























      1












      1








      1








      I have an app running in macOS Mojave and it works nicely. I can drag a pdf file onto a PDFView and can put a button to mark a watermark on the pdf file. I got the example code from apple WWDC written for iOS, and I translated it for macOS. My problem is how can I save this pdf including the watermark, to desktop for example?





      My Code:



      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()

      }
      }









      share|improve this question
















      I have an app running in macOS Mojave and it works nicely. I can drag a pdf file onto a PDFView and can put a button to mark a watermark on the pdf file. I got the example code from apple WWDC written for iOS, and I translated it for macOS. My problem is how can I save this pdf including the watermark, to desktop for example?





      My Code:



      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()

      }
      }






      swift cocoa pdf






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 15:23









      shim

      4,03564677




      4,03564677










      asked Nov 21 '18 at 15:18









      ebnerebner

      42




      42
























          3 Answers
          3






          active

          oldest

          votes


















          0














          Guys sorry that was a total misunderstanding of mine. Total error of reason. I can watermark the document then I can just save it or print it and the watermark will be present. I do not need a separate save function. Ou man I make my head so good sometimes you sit on the hose. Thank you very much for your great help.






          share|improve this answer































            -1














            If you want to save it to the Desktop.



            You have to change the path, where the file is written



            for example standard 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)





            share|improve this answer
























            • 1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

              – Willeke
              Nov 21 '18 at 16:25



















            -1














            But my problem how I can save the pdf file with the watermark. When I save the file like your workaround then saves only the pdf file without the watermark. That is not what I want. Thx for every workaround who helps to solves the problem.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415176%2fhow-can-i-save-a-watermark-on-pdf-file-and-export-to-desktop-macos-mojave%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              Guys sorry that was a total misunderstanding of mine. Total error of reason. I can watermark the document then I can just save it or print it and the watermark will be present. I do not need a separate save function. Ou man I make my head so good sometimes you sit on the hose. Thank you very much for your great help.






              share|improve this answer




























                0














                Guys sorry that was a total misunderstanding of mine. Total error of reason. I can watermark the document then I can just save it or print it and the watermark will be present. I do not need a separate save function. Ou man I make my head so good sometimes you sit on the hose. Thank you very much for your great help.






                share|improve this answer


























                  0












                  0








                  0







                  Guys sorry that was a total misunderstanding of mine. Total error of reason. I can watermark the document then I can just save it or print it and the watermark will be present. I do not need a separate save function. Ou man I make my head so good sometimes you sit on the hose. Thank you very much for your great help.






                  share|improve this answer













                  Guys sorry that was a total misunderstanding of mine. Total error of reason. I can watermark the document then I can just save it or print it and the watermark will be present. I do not need a separate save function. Ou man I make my head so good sometimes you sit on the hose. Thank you very much for your great help.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 2 '18 at 16:40









                  ebnerebner

                  42




                  42

























                      -1














                      If you want to save it to the Desktop.



                      You have to change the path, where the file is written



                      for example standard 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)





                      share|improve this answer
























                      • 1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

                        – Willeke
                        Nov 21 '18 at 16:25
















                      -1














                      If you want to save it to the Desktop.



                      You have to change the path, where the file is written



                      for example standard 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)





                      share|improve this answer
























                      • 1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

                        – Willeke
                        Nov 21 '18 at 16:25














                      -1












                      -1








                      -1







                      If you want to save it to the Desktop.



                      You have to change the path, where the file is written



                      for example standard 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)





                      share|improve this answer













                      If you want to save it to the Desktop.



                      You have to change the path, where the file is written



                      for example standard 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)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 21 '18 at 16:16









                      ivionivion

                      268136




                      268136













                      • 1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

                        – Willeke
                        Nov 21 '18 at 16:25



















                      • 1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

                        – Willeke
                        Nov 21 '18 at 16:25

















                      1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

                      – Willeke
                      Nov 21 '18 at 16:25





                      1. Use NSDesktopDirectory instead of NSHomeDirectory. 2. Don't use paths, use URLs and appendingPathComponent(_:).

                      – Willeke
                      Nov 21 '18 at 16:25











                      -1














                      But my problem how I can save the pdf file with the watermark. When I save the file like your workaround then saves only the pdf file without the watermark. That is not what I want. Thx for every workaround who helps to solves the problem.






                      share|improve this answer




























                        -1














                        But my problem how I can save the pdf file with the watermark. When I save the file like your workaround then saves only the pdf file without the watermark. That is not what I want. Thx for every workaround who helps to solves the problem.






                        share|improve this answer


























                          -1












                          -1








                          -1







                          But my problem how I can save the pdf file with the watermark. When I save the file like your workaround then saves only the pdf file without the watermark. That is not what I want. Thx for every workaround who helps to solves the problem.






                          share|improve this answer













                          But my problem how I can save the pdf file with the watermark. When I save the file like your workaround then saves only the pdf file without the watermark. That is not what I want. Thx for every workaround who helps to solves the problem.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 23 '18 at 19:52









                          ebnerebner

                          42




                          42






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415176%2fhow-can-i-save-a-watermark-on-pdf-file-and-export-to-desktop-macos-mojave%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Costa Masnaga

                              Fotorealismo

                              Sidney Franklin