I am trying to create a PDF document from hundreds of pages of a SwiftUI view's. Currently my approach is the following. This works fine but it is quite slow. Was wondering if there is a better way of doing this either by using UIKit or some other method?
@MainActor
func renderPages() async {
let pathComponent = "example.pdf"
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(pathComponent)
var box = CGRect(x: 0, y: 0, width: 1000, height: 500)
guard let pdf = CGContext(url as CFURL, mediaBox: &box, nil) else {
return
}
for pageIndex in pageIndices {
pdf.beginPDFPage(nil)
let renderer = ImageRenderer(content:
MySwiftUIView(index: pageIndex)
)
renderer.render { size, myContext in
myContext(pdf)
}
pdf.endPDFPage()
}
pdf.closePDF()
self.url = url
}