Search code examples
macoscocoansprintoperationnsprintinfonsprintpanel

Setting showsPrintPanel to false when using NSPrintOperation causes different sizes when printing


When using NSPrintOperation and setting showsPrintPanel to true, the view prints just fine, however when I set the property to false, the view does not print correctly and is bigger than the paper:

func printBadge(printerName: String){
    let printingFrame = NSRect(x: 0, y: 0, width: AppManager.sharedInstance.badge.width, height: AppManager.sharedInstance.badge.height)
    let badgeView = BadgeView(frame: printingFrame)
    let printOperation = NSPrintOperation(view: badgeView)
    let printInfo = printOperation.printInfo

    printInfo.printer = NSPrinter(name: printerName)!
    printInfo.paperSize = NSSize(width: AppManager.sharedInstance.badge.width, height: AppManager.sharedInstance.badge.height)
    printInfo.horizontalPagination = .AutoPagination
    printInfo.verticalPagination = .AutoPagination
    printInfo.topMargin = 0
    printInfo.bottomMargin = 0
    printInfo.rightMargin = 0
    printInfo.leftMargin = 0
    printInfo.horizontallyCentered = true
    printInfo.verticallyCentered = true
    printOperation.showsPrintPanel = AppManager.sharedInstance.showsPrintPanel!
    printOperation.runOperation()
}

Solution

  • I resolved the issue in the end, NSPrintInfo.paperSize takes POINTS and not PIXELS, so my calculation from millimetres to pixels was incorrect (the printer settings are in millimetres and not pixels or points).

    If anyone is interest, the math calculation from millimetres to points is;

    millimetres * 72 / 25.4