ios - 在 PDF 上下文中渲染视图 - SwiftUI
问题描述
我正在尝试将包含大量形状和文本的视图转换为用户可以从我的应用程序导出的 PDF。我在导出 PDF 时遇到了真正的问题,我找不到与 SwiftUI 相关的太多帮助。我收到了反馈:
“你不需要控制器,你可以在同一个 PDF 上下文中逐个视图渲染”
但是我不知道这意味着什么或如何实现它,我的 PDF 生成代码如下。
let width: CGFloat = 8.5 * 72.0
//Estimate the height of your view
let height: CGFloat = 1000
let charts = MatchReportView(homeTeam: homeTeam, awayTeam: awayTeam)
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: 8.5 * 72.0, height: 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)")
} catch {
print("Could not create PDF file: \(error.localizedDescription)")
}
}
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
关于如何生成此 PDF 的任何想法?目前它只是返回一个空白文档。它是滚动视图的事实会起作用吗?
解决方案
推荐阅读
- html - minlength 属性似乎不起作用
- python - max() 函数如何在以下代码中工作
- javascript - 如何将整个数组添加到 useState 变量
- sql - SQL database_id 值是否被重用?
- python - random.random() 在不同的机器上生成不同的数字
- scala - 哪些操作在流库中的拉取模型和推送模型中更容易实现(反之亦然)?
- r - Google Cloud Compute Engine 上的 xgboost 超慢
- c# - 如何使用 C# 和 Google 日历 API 创建 Google 日历活动?
- c# - ExecuteAsync 更改传递的动态参数名称
- python - 在 VS Code 中无法切换到 Python3