I have a mac app using swiftUI framework. I get a pdf url from an api and I need to allow the user to click a button that prints the pdf.
I have it working as of right now, The alignment of the pdf is just off. What I mean is it looks like a pasted a pdf on top of another pdf so my margins are bigger than normal and I have a weird outline of the url pdf on the printed pdf.
To my understanding I can out of the box use UIKit in a mac app to use the UIPrintInteractionController.
I am using the NSPrintOperation right now.
import SwiftUI
import PDFKit
import AppKit
struct ContentView: View {
let pdfDocumentUrl = URL(string: "https://www.soundczech.cz/temp/lorem-ipsum.pdf")!
var body: some View {
VStack {
Button("Print PDF") {
let pdf = PDFDocument(url: pdfDocumentUrl)!
printPDFDocumentt(pdf)
}
}
.padding()
}
func printPDFDocumentt(_ document: PDFDocument) {
let pdfView = PDFView(frame: .init(x: 0, y: 0, width: document.page(at:
0)?.bounds(for: .mediaBox).width ?? 0,
![]("https://developer.apple.com/forums/content/attachment/5554c20f-7247-4300-b0b1-1f7a7ab6ebbe" "title=CleanShot 2023-05-09 at 11.46.25@2x.png;width=1528;height=2040")
height: document.page(at: 0)?.bounds(for: .mediaBox).height ?? 0))
pdfView.document = document
pdfView.backgroundColor = .clear
let printInfo = NSPrintInfo.shared
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .fit
printInfo.orientation = .portrait
printInfo.topMargin = 0
printInfo.bottomMargin = 0
printInfo.leftMargin = 0
printInfo.rightMargin = 0
let printOperation = NSPrintOperation(view: pdfView, printInfo: printInfo)
printOperation.run()
}
}
Found the solution to my problem. In my code above, I had a pdfDocument object and then I created the PDFView and tried to send it to the printer using NSPrintOperation.
I think setting the PDFView document as the downloaded pdf was the issue. So What I came up with was using the PDFDocument.printOperation and changed my printDocumentFunction
private func printPDFDocumentt(_ document: PDFDocument) {
let printInfo = NSPrintInfo.shared
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .fit
printInfo.orientation = .portrait
printInfo.topMargin = 0
printInfo.bottomMargin = 0
printInfo.leftMargin = 0
printInfo.rightMargin = 0
printInfo.isHorizontallyCentered = true
printInfo.isVerticallyCentered = true
let scale: PDFPrintScalingMode = .pageScaleDownToFit
let printOp = document.printOperation(for: printInfo, scalingMode: scale, autoRotate: true)
DispatchQueue.main.async {
printOp?.run()
}
}