如何使用SwiftUI将多个图像渲染为多页pdf文档

dgtucam1  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(119)

我成功地创建一个PDF文档从3图像使用以下代码:

struct ExportImagesView: View {
    
    var body: some View {
        ShareLink("Export Licence as PDF", item: render())
    }

    func render() -> URL {
        // 1: Render Hello World with some modifiers
        let renderer = ImageRenderer(content:
                                        VStack {
                                            Image("Page1")
                                            Image("Page2")
                                            Image("Page3")
            
                                        }
        )

        // 2: Save it to our documents directory
        let url = URL.documentsDirectory.appending(path: "output.pdf")

        // 3: Start the rendering process
        renderer.render { size, context in
            // 4: Tell SwiftUI our PDF should be the same size as the views we're rendering
            var box = CGRect(x: 0, y: 0, width: size.width, height: size.height)

            // 5: Create the CGContext for our PDF pages
            guard let pdf = CGContext(url as CFURL, mediaBox: &box, nil) else {
                return
            }

            // 6: Start a new PDF page
            pdf.beginPDFPage(nil)

            // 7: Render the SwiftUI view data onto the page
            context(pdf)

            // 8: End the page and close the file
            pdf.endPDFPage()
            pdf.closePDF()
        }

        return url
    }
}

以上内容摘自以下链接中的教程:
https://www.hackingwithswift.com/quick-start/swiftui/how-to-render-a-swiftui-view-to-a-pdf
我怎样才能迭代通过图像创建一个3页的pdf文档,每页一个图像?我将指定页面大小。

z31licg0

z31licg01#

你已经有了。简单地重新排列操作顺序:

struct ExportImagesView: View {
    let pages = [ "Page1", "Page2", "Page3" ]
    
    var body: some View {
        VStack {
            ShareLink("Export Licence as PDF", item: render())
        }
    }
    
    @MainActor func render() -> URL {
        
        // 1: Save path
        let url = URL.documentsDirectory.appending(path: "output.pdf")
        
        // 2: PDF size
        var box = CGRect(x: 0, y: 0, width: 600, height: 800)
        
        // 3: Create the CGContext for our PDF pages
        guard let pdf = CGContext(url as CFURL, mediaBox: &box, nil) else {
            return url
        }
        
        // 4: Render each page
        for page in pages {
            
            pdf.beginPDFPage(nil)
            
            let renderer = ImageRenderer(content:
                Image(page)
            )
            
            renderer.render { size, context in
                context(pdf)
            }
            
            pdf.endPDFPage()
            
        }
        pdf.closePDF()
        
        return url
    }
}

相关问题