首页 > 解决方案 > 在 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 的任何想法?目前它只是返回一个空白文档。它是滚动视图的事实会起作用吗?

标签: iosswiftxcodepdfswiftui

解决方案


推荐阅读