Hi,
I am trying to export the following SwiftUI View to PDF using UIGraphicsPDFRenderer.
The problem I am getting is there is somehow a margin on top of the exported PDF.
The code I am using
import SwiftUI struct ContentView: View { var body: some View { let pressGesture = TapGesture()
.onEnded { value in
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let outputFileURL = documentDirectory.appendingPathComponent("SwiftUI.pdf")
let pdfVC = UIHostingController(rootView: self)
let pageSize = CGSize(width: 2.625 * 72.0, height: 1.0 * 72.0)
pdfVC.view.frame = CGRect(origin: .zero, size: pageSize)
let rootVC = UIApplication.shared.windows.first?.rootViewController
rootVC?.addChild(pdfVC)
rootVC?.view.insertSubview(pdfVC.view, at: 0)
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height))
DispatchQueue.main.async {
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
context.beginPage()
pdfVC.view.layer.render(in: context.cgContext)
})
print("wrote file to: (outputFileURL.path)")
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
} catch {
print("Could not create PDF file: (error.localizedDescription)")
}
}
}
VStack(){
Text("Hello")
}
.frame(width: 2.625 * 72.0, height: 1.0 * 72.0, alignment: .center)
.gesture(pressGesture)
.background(Color.red)
}
}
May I know what am I doing wrong? Thanks in advance.