Как заставить NSPrintInfo и NSPrintOperation использовать бумагу без полей в заданных размерах?

Использование NSPrintInfo (совместно или нет), если я указываю размер бумаги с помощью printInfo?.paperSize, которого нет в списке размеров бумаги, определенных в раскрывающемся списке размеров бумаги на панели NSPrintOperation, и устанавливаю поля на ноль.

      printInfo?.leftMargin = 0
printInfo?.rightMargin = 0
printInfo?.topMargin = 0
printInfo?.bottomMargin = 0

панель NSPrintOperation будет учитывать размер и поля, и печать будет отлично работать с полями, установленными на 0,0. Но если я использую размер бумаги, определенный в раскрывающемся списке, например 8,5 x 11,0, даже несмотря на то, что я сказал использовать 0,0 для полей, будет использоваться бумага с «границами» около 0,20». Если я изменю этот раскрывающийся список на « US Letter без полей, 8,5 x 11,0 дюймов, поля равны 0,0, printInfo.imageablePageBounds указан правильно, печать работает нормально.

Возможно ли вообще сделать панель NSPrintOperation по умолчанию без полей для размеров бумаги, для которых она имеет определение?

Это похоже на этот вопрос, на который ФП не нашел оптимального ответа:

в настройках принтера неправильные поля/размер страницы

Приложение представляет собой программу редактирования изображений WYSIWYG с возможностью перетаскивания. Я понимаю, что очень немногие принтеры могут успешно печатать до края бумаги. Что я делаю, так это контролирую поля в коде, чтобы пользователю не приходилось заниматься этим беспорядком во время печати. Пользователь устанавливает поля во время разработки, чтобы визуально видеть, где произойдет обрезка.

Исходный код для теста:

      
//
//  AppDelegate.swift
//  PrinterTest
//
//  Created 4/7/23.
//

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet var window: NSWindow!

  var printInfo: NSPrintInfo?
  var printOperation: NSPrintOperation?
  
  // NSView class used in the Print Panel's preview window - created with the dimensions of the user's paper request
  // just draws a red frame around it's bounds.
  
  class PrintPreview: NSView {
  
    var currentContext : CGContext {                            // convenience method for getting the Graphics Context
      let context = NSGraphicsContext.current
      return context!.cgContext
      }

    override func draw(_ dirtyRect: NSRect) {
      super.draw(dirtyRect)
      let context = currentContext
      context.saveGState()
      context.setLineWidth(4.0)
      context.setStrokeColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
      context.stroke(bounds)                                    // draw a red frame around the perimeter of the "project"
      context.restoreGState()
      }
      
   override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)
    }
    
  required init?(coder: NSCoder) {
    fatalError("PrintPreview init(coder:) has not been implemented")
    }
    
  }

  // notification sent when something in printInfoChanged

  @objc private func printInfoDidChange(notification: NSNotification) {
    let printSettings = printOperation!.printInfo.dictionary()
    
    print("-------- printInfoDidChange -------- ")
    for (key, value) in printSettings {
      print("\(key): \(value)")
      }
    print("------------------------------------ ")
    }

  @IBAction func startPrint(_ sender: Any) {
  
    let paperSize = NSSize(width: 8.5 * 72.0, height: 11.0 * 72.0)              // define paper size
    //let paperSize = NSSize(width: 7.0 * 72.0, height: 8.0 * 72.0)
    
    // create a simple NSView that will draw a red frame around it's bounds
    
    let printPreview = PrintPreview(frame: CGRect(x: 0, y: 0, width: paperSize.width, height: paperSize.height))
    
    // build the NSPrintInfo structure specifying 0 margins
    
    printInfo = NSPrintInfo.shared
    printInfo?.orientation = NSPrintInfo.PaperOrientation.portrait
    printInfo?.isHorizontallyCentered = true
    printInfo?.isVerticallyCentered = true
    printInfo?.horizontalPagination = NSPrintInfo.PaginationMode.fit
    printInfo?.verticalPagination = NSPrintInfo.PaginationMode.fit
    printInfo?.leftMargin = 0
    printInfo?.rightMargin = 0
    printInfo?.topMargin = 0
    printInfo?.bottomMargin = 0
    printInfo?.paperSize = paperSize
    
    // build the printOperation object
    
    printOperation = NSPrintOperation(view: printPreview, printInfo: printInfo!)
    printOperation!.printPanel.options = [.showsCopies, .showsPaperSize, .showsPageSetupAccessory, .showsPreview]
    printOperation?.jobTitle = "Print Test"
    printOperation?.showsPrintPanel = true
    printOperation!.run()
    }

  // app finished launching, setup a notification for when the print info object changes
  
  func applicationDidFinishLaunching(_ aNotification: Notification) {
      NotificationCenter.default.addObserver( self,
                                            selector: #selector(self.printInfoDidChange),
                                            name: Notification.Name("NSPrintInfoDidChange"),
                                            object: nil)
     }

  func applicationWillTerminate(_ aNotification: Notification) {
    }

  func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
    return true
    }
    
  func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    return true
    }
}

0 ответов

Другие вопросы по тегам