MacOS Printing and Settings











up vote
0
down vote

favorite












I'm a Windows dev tasked with creating an app on MacOS. It's a favor for one of the nuns at my kids school. In this function, I need to print an image file. The first time I want to show the printer dialog but thereafter just print without user interaction.



I have hobbled this code together. It seems to work but it would be helpful to have a real Mac dev look at it and let me know of any improvements. My previous experience with MacOS and Swift are nil.



static func printPic(path : String) {

let defaults = UserDefaults.standard

// Load the image and put into an NSImageView
let image = NSImage(contentsOfFile: path)
let rect = NSRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
let pictureBox = NSImageView(frame: rect)
pictureBox.image = image!

let printInfo = NSPrintInfo()

// Check if settings have already been saved
if (defaults.object(forKey: "printerSettings") != nil) {
// Use settings - don't show print dialog
let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)
// Load settings from UserDefaults
if let data = defaults.object(forKey: "printerSettings") as? NSData {
let unarc = NSKeyedUnarchiver(forReadingWith: data as Data)
let settings = unarc.decodeObject(forKey: "root") as! NSMutableDictionary
// Convert NSMutableDictionary to regular dictionary
let userData = settings as NSDictionary? as? [AnyHashable: Any] ?? [:]
printOperation.printInfo.printSettings.setDictionary(userData)
}
printOperation.showsPrintPanel = false
printOperation.showsProgressPanel = false
printOperation.run()
}
else {
// First time, set some defaults and show print dialog
printInfo.bottomMargin = 0
printInfo.topMargin = 0
printInfo.leftMargin = 0
printInfo.rightMargin = 0
printInfo.orientation = NSPaperOrientation.landscape
printInfo.paperSize = NSSize(width: 6 * 72, height: 4 * 72)

let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)

printOperation.showsPrintPanel = true
printOperation.showsProgressPanel = true
printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPaperSize)
printOperation.printPanel.options.insert(NSPrintPanelOptions.showsOrientation)
printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPreview)

printOperation.run()

// Save settings for next time
defaults.set(NSKeyedArchiver.archivedData(withRootObject: printOperation.printInfo.printSettings), forKey: "printerSettings")
defaults.synchronize()
}
}









share|improve this question


























    up vote
    0
    down vote

    favorite












    I'm a Windows dev tasked with creating an app on MacOS. It's a favor for one of the nuns at my kids school. In this function, I need to print an image file. The first time I want to show the printer dialog but thereafter just print without user interaction.



    I have hobbled this code together. It seems to work but it would be helpful to have a real Mac dev look at it and let me know of any improvements. My previous experience with MacOS and Swift are nil.



    static func printPic(path : String) {

    let defaults = UserDefaults.standard

    // Load the image and put into an NSImageView
    let image = NSImage(contentsOfFile: path)
    let rect = NSRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
    let pictureBox = NSImageView(frame: rect)
    pictureBox.image = image!

    let printInfo = NSPrintInfo()

    // Check if settings have already been saved
    if (defaults.object(forKey: "printerSettings") != nil) {
    // Use settings - don't show print dialog
    let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)
    // Load settings from UserDefaults
    if let data = defaults.object(forKey: "printerSettings") as? NSData {
    let unarc = NSKeyedUnarchiver(forReadingWith: data as Data)
    let settings = unarc.decodeObject(forKey: "root") as! NSMutableDictionary
    // Convert NSMutableDictionary to regular dictionary
    let userData = settings as NSDictionary? as? [AnyHashable: Any] ?? [:]
    printOperation.printInfo.printSettings.setDictionary(userData)
    }
    printOperation.showsPrintPanel = false
    printOperation.showsProgressPanel = false
    printOperation.run()
    }
    else {
    // First time, set some defaults and show print dialog
    printInfo.bottomMargin = 0
    printInfo.topMargin = 0
    printInfo.leftMargin = 0
    printInfo.rightMargin = 0
    printInfo.orientation = NSPaperOrientation.landscape
    printInfo.paperSize = NSSize(width: 6 * 72, height: 4 * 72)

    let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)

    printOperation.showsPrintPanel = true
    printOperation.showsProgressPanel = true
    printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPaperSize)
    printOperation.printPanel.options.insert(NSPrintPanelOptions.showsOrientation)
    printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPreview)

    printOperation.run()

    // Save settings for next time
    defaults.set(NSKeyedArchiver.archivedData(withRootObject: printOperation.printInfo.printSettings), forKey: "printerSettings")
    defaults.synchronize()
    }
    }









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm a Windows dev tasked with creating an app on MacOS. It's a favor for one of the nuns at my kids school. In this function, I need to print an image file. The first time I want to show the printer dialog but thereafter just print without user interaction.



      I have hobbled this code together. It seems to work but it would be helpful to have a real Mac dev look at it and let me know of any improvements. My previous experience with MacOS and Swift are nil.



      static func printPic(path : String) {

      let defaults = UserDefaults.standard

      // Load the image and put into an NSImageView
      let image = NSImage(contentsOfFile: path)
      let rect = NSRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
      let pictureBox = NSImageView(frame: rect)
      pictureBox.image = image!

      let printInfo = NSPrintInfo()

      // Check if settings have already been saved
      if (defaults.object(forKey: "printerSettings") != nil) {
      // Use settings - don't show print dialog
      let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)
      // Load settings from UserDefaults
      if let data = defaults.object(forKey: "printerSettings") as? NSData {
      let unarc = NSKeyedUnarchiver(forReadingWith: data as Data)
      let settings = unarc.decodeObject(forKey: "root") as! NSMutableDictionary
      // Convert NSMutableDictionary to regular dictionary
      let userData = settings as NSDictionary? as? [AnyHashable: Any] ?? [:]
      printOperation.printInfo.printSettings.setDictionary(userData)
      }
      printOperation.showsPrintPanel = false
      printOperation.showsProgressPanel = false
      printOperation.run()
      }
      else {
      // First time, set some defaults and show print dialog
      printInfo.bottomMargin = 0
      printInfo.topMargin = 0
      printInfo.leftMargin = 0
      printInfo.rightMargin = 0
      printInfo.orientation = NSPaperOrientation.landscape
      printInfo.paperSize = NSSize(width: 6 * 72, height: 4 * 72)

      let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)

      printOperation.showsPrintPanel = true
      printOperation.showsProgressPanel = true
      printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPaperSize)
      printOperation.printPanel.options.insert(NSPrintPanelOptions.showsOrientation)
      printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPreview)

      printOperation.run()

      // Save settings for next time
      defaults.set(NSKeyedArchiver.archivedData(withRootObject: printOperation.printInfo.printSettings), forKey: "printerSettings")
      defaults.synchronize()
      }
      }









      share|improve this question













      I'm a Windows dev tasked with creating an app on MacOS. It's a favor for one of the nuns at my kids school. In this function, I need to print an image file. The first time I want to show the printer dialog but thereafter just print without user interaction.



      I have hobbled this code together. It seems to work but it would be helpful to have a real Mac dev look at it and let me know of any improvements. My previous experience with MacOS and Swift are nil.



      static func printPic(path : String) {

      let defaults = UserDefaults.standard

      // Load the image and put into an NSImageView
      let image = NSImage(contentsOfFile: path)
      let rect = NSRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
      let pictureBox = NSImageView(frame: rect)
      pictureBox.image = image!

      let printInfo = NSPrintInfo()

      // Check if settings have already been saved
      if (defaults.object(forKey: "printerSettings") != nil) {
      // Use settings - don't show print dialog
      let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)
      // Load settings from UserDefaults
      if let data = defaults.object(forKey: "printerSettings") as? NSData {
      let unarc = NSKeyedUnarchiver(forReadingWith: data as Data)
      let settings = unarc.decodeObject(forKey: "root") as! NSMutableDictionary
      // Convert NSMutableDictionary to regular dictionary
      let userData = settings as NSDictionary? as? [AnyHashable: Any] ?? [:]
      printOperation.printInfo.printSettings.setDictionary(userData)
      }
      printOperation.showsPrintPanel = false
      printOperation.showsProgressPanel = false
      printOperation.run()
      }
      else {
      // First time, set some defaults and show print dialog
      printInfo.bottomMargin = 0
      printInfo.topMargin = 0
      printInfo.leftMargin = 0
      printInfo.rightMargin = 0
      printInfo.orientation = NSPaperOrientation.landscape
      printInfo.paperSize = NSSize(width: 6 * 72, height: 4 * 72)

      let printOperation = NSPrintOperation(view: pictureBox, printInfo: printInfo)

      printOperation.showsPrintPanel = true
      printOperation.showsProgressPanel = true
      printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPaperSize)
      printOperation.printPanel.options.insert(NSPrintPanelOptions.showsOrientation)
      printOperation.printPanel.options.insert(NSPrintPanelOptions.showsPreview)

      printOperation.run()

      // Save settings for next time
      defaults.set(NSKeyedArchiver.archivedData(withRootObject: printOperation.printInfo.printSettings), forKey: "printerSettings")
      defaults.synchronize()
      }
      }






      swift macos






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 at 14:44









      Johnny Mopp

      16518




      16518



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          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: "196"
          };
          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',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fcodereview.stackexchange.com%2fquestions%2f207563%2fmacos-printing-and-settings%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207563%2fmacos-printing-and-settings%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

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар