在 iOS 上将 SwiftUI 视图转换为 PDF [英] Convert SwiftUI View to PDF on iOS

查看:21
本文介绍了在 iOS 上将 SwiftUI 视图转换为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 SwiftUI 绘制了一些漂亮的图形,因为它非常简单易行.然后我想将整个 SwiftUI 视图导出为 PDF,以便其他人可以以一种很好的方式查看图形.SwiftUI 没有直接为此提供解决方案.

I was drawing some nice graphs with SwiftUI, because it is so simple and easy to do. Then I wanted to export the whole SwiftUI View to a PDF such that someone else can view the graphs in a nice way. SwiftUI does not offer a solution for this directly.

干杯,
亚历克斯

Cheers,
Alex

推荐答案

经过一番思考,我想到了将 UIKit 转 PDF 方法和 SwiftUI 结合起来的想法.

After some thinking I came up with the idea of combining the UIKit to PDF method and SwiftUI.

首先创建 SwiftUI 视图,然后放入 UIHostingController.您在所有其他视图后面的窗口上渲染 HostingController 并在 PDF 上绘制其图层.下面列出了示例代码.

At first you create your SwiftUI view, then you put into an UIHostingController. You render the HostingController on a window behind all other views and and draw its layer on a PDF. Sample code is listed below.

func exportToPDF() {

    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let outputFileURL = documentDirectory.appendingPathComponent("SwiftUI.pdf")

    //Normal with
    let width: CGFloat = 8.5 * 72.0
    //Estimate the height of your view
    let height: CGFloat = 1000
    let charts = ChartsView()

    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))

    do {
        try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
            context.beginPage()
            pdfVC.view.layer.render(in: context.cgContext)
        })

        self.exportURL = outputFileURL
        self.showExportSheet = true

    }catch {
        self.showError = true
        print("Could not create PDF file: (error)")
    }

    pdfVC.removeFromParent()
    pdfVC.view.removeFromSuperview()
}

这篇关于在 iOS 上将 SwiftUI 视图转换为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆