TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to generate a PDF from a ScrollView

Forums > SwiftUI

I have a scroll view, that will generate a number of different views to create a timeline. I want this scrollview, of unknown length to be exported to multiple PDF pages. How would I do this? I have found a way of converting an entire view to a PDF (https://stackoverflow.com/questions/60753436/convert-swiftui-view-to-pdf-on-ios?noredirect=1&lq=1), and I couldn't really get that to work on a view let alone a ScrollView. Any ideas?

Here is my scroll view code - both HomeArm and AwayArm are separate views that build the timeline icon, I don't think they're relevant to creating the PDF though:

ScrollView(.vertical){
    VStack(spacing: 0){         
        ForEach(processor.matchEvents){event in
            if(event.team.home == true){
                HomeArm(team: event.team, event: event)
            }
            else{
                AwayArm(team: event.team, event: event)
            }
       }
    }
}
.frame(width: 475, height: 1100, alignment: .center)

4      

You need to setup the data you want to send to pdf. Format the information in a similar way to how you formatted the views (if that's waht you want) then render the pdf. You may not get the 100% exact view you are after, but it's a pdf not a screenshot of the screen. So think about it differently.

This should help: https://www.hackingwithswift.com/example-code/uikit/how-to-render-pdfs-using-uigraphicspdfrenderer

3      

It may help you

func createPdf() {

        let outputFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("yourFileName.pdf")
        let title = "Your Title\n"
        let text = String(repeating: "Your string row from List View or ScrollView \n ", count: 2000)

        let titleAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 36)]
        let textAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]

        let formattedTitle = NSMutableAttributedString(string: title, attributes: titleAttributes)
        let formattedText = NSAttributedString(string: text, attributes: textAttributes)
        formattedTitle.append(formattedText)

        // 1. Create Print Formatter with your text.

        let formatter = UISimpleTextPrintFormatter(attributedText: formattedTitle)

        // 2. Add formatter with pageRender

        let render = UIPrintPageRenderer()
        render.addPrintFormatter(formatter, startingAtPageAt: 0)

        // 3. Assign paperRect and printableRect

        let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
        let printable = page.insetBy(dx: 0, dy: 0)

        render.setValue(NSValue(cgRect: page), forKey: "paperRect")
        render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

        // 4. Create PDF context and draw
        let rect = CGRect.zero

        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, rect, nil)

        for i in 1...render.numberOfPages {

            UIGraphicsBeginPDFPage();
            let bounds = UIGraphicsGetPDFContextBounds()
            render.drawPage(at: i - 1, in: bounds)
        }

        UIGraphicsEndPDFContext();

        // 5. Save PDF file

        do {
            try pdfData.write(to: outputFileURL, options: .atomic)

            print("wrote PDF file with multiple pages to: \(outputFileURL.path)")
        } catch {

             print("Could not create PDF file: \(error.localizedDescription)")
        }
    }

3      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.