问题描述
我是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)
}
}
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 (将#修改为@)