Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

macos - swift printing a view at top left corner of the page

I have a print routine that prints a view to the selected printer. Works fine but the output is always in the centre of the page.

I would like to be able to print the view with the origin at the top left corner of the page, tried everything I can think of but always in the centre.

My print function:

func printView(viewToPrint: AnyView){
    let printContainerView = NSHostingView(rootView: viewToPrint)
    printContainerView.frame.size = CGSize(width: 196, height: 200)
    let printInfo = NSPrintInfo()
    printInfo.horizontalPagination = .automatic
    printInfo.verticalPagination = .automatic
    printInfo.leftMargin = 0.0
    printInfo.rightMargin = 0.0
    printInfo.topMargin = 0.0
    printInfo.bottomMargin = 0.0
    let printOperation = NSPrintOperation(view: printContainerView, printInfo: printInfo)
    printOperation.showsPrintPanel = true
    printOperation.showsProgressPanel = true
    printOperation.canSpawnSeparateThread = true
    printOperation.run()
}

Because I don't know what printer is being used and some do not report the paper size (think that's a driver problem) I cant create a view to the size of the page and position the view to print appropriately - tried it and still in the centre!

My conclusion is that I am doing something fundamentally wrong but it does print!

Thanks for any suggestions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try the following

let printInfo = NSPrintInfo.shared
printInfo.isHorizontallyCentered = false
printInfo.isVerticallyCentered = false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...