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

查看:97
本文介绍了在iOS上将SwiftUI View转换为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 View转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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