如何解决在iOS上将可滚动的SwiftUI视图转换为PDF
我是SwiftUI的新手。我正在使用此链接Convert SwiftUI View to PDF on iOS将可滚动的SwiftUI视图转换为pdf,但无法生成pdf。输出将为空。
这是我的代码
这是我要转换为pdf的视图
GeometryReader{geo in
FirstView(getResumeId: self.getResumeId).onAppear{
self.exportToPDF(widht:geo.size.width,height:geo.size.height)
}
}
这是我从视图生成pdf的功能
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,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()
}
}
帮帮我。我非常感谢他。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。