I am new to SwiftUI. I am converting a scrollable SwiftUI view to pdf but unable to do that. The output will be empty.
Here is my code
This is the view that I want to convert into pdf
GeometryReader{geo in
FirstView(getResumeId: self.getResumeId).onAppear{
self.exportToPDF(widht:geo.size.width,height:geo.size.height)
}
}
This is my function that generates the pdf from view
func exportToPDF(width:CGFloat, height:CGFloat) {
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let outputFileURL = documentDirectory.appendingPathComponent("\(self.getResumeId).pdf")
//Normal with
let width: CGFloat = width
//Estimate the height of your view
let height: CGFloat = height
let charts = FirstView(getResumeId: self.getResumeId)
let pdfVC = UIHostingController(rootView: charts)
pdfVC.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
//Render the view behind all other views
let rootVC = UIApplication.shared.windows.first?.rootViewController
rootVC?.addChild(pdfVC)
rootVC?.view.insertSubview(pdfVC.view, at: 0)
//Render the PDF
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: width, height: height))
DispatchQueue.main.async {
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
context.beginPage()
rootVC?.view.layer.render(in: context.cgContext)
})
UserDefaults.standard.set(outputFileURL, forKey: "pdf")
UserDefaults.standard.synchronize()
print("wrote file to: \(outputFileURL.path)")
} catch {
print("Could not create PDF file: \(error.localizedDescription)")
}
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
}
}
The empty pdf generate or sometimes pdf did not open. I searched alot but unable to do that. If anyone help me I am verythankful to him.