-1

I want to create a PDF with multiple pages if the swiftUI view content height is more than 1500 on iPAD.

The multiple solutions on Google that I've tried did not work.

I need to convert my whole SwiftUI view into multiple Pages of PDF on iPad.

The size of the SwiftUI View = CGSize(width: 1118.0, , height: 1700.0)

enter image description here

I have added the image here of my view and I want that view into multiple pages of PDF cause the height of my view is more than A4 size height.

@MainActor func render(view: some View) -> URL? {
// 1: Render Hello World with some modifiers
if #available(iOS 16.0, *) {
    let renderer = ImageRenderer(content: view)
    // 2: Save it to our documents directory
    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let url = documentDirectory.appendingPathComponent("SwiftUIPDF1.pdf")
    
    print(url)

    // 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
} else {
    // Fallback on earlier versions
}
return nil
}
Swift Dev Journal
  • 19,282
  • 4
  • 56
  • 66

1 Answers1

0

I don't have a copy and paste code solution for you, but I can provide an algorithm of what you need to do to create a multiple page PDF.

The reason your code creates a PDF with one page is because the code creates only one PDF page. You call beginPDFPage and endPDFPage only once. You must call those functions once for each page in the PDF.

Start by creating a variable that stores the location in the view to start drawing a PDF page. Give this variable an initial value of 0.

While the start location is less than the size of the view, do the following:

  • Call beginPDFPage.
  • Draw one PDF page from the view, starting from the start location.
  • Call endPDFPage.
  • Update the start location value by adding the amount you drew in the current page.

Call closePDF when you are finished creating the PDF pages.

Swift Dev Journal
  • 19,282
  • 4
  • 56
  • 66