UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Creating PDF from UIView in Swift

Forums > Swift

I have been stuck/ researching this problem for days, the method below successfully creates the pdf from a regular size UIView. However, I need the contents of my containerView that is located inside a UIScrollview. The height of my containerView is 5000. Can someone help me to render the containerView into multiple PDF pages or direct me to a better way of doing this.

func exportAsPdfFromView() -> String {

        let pdfPageFrame = self.bounds
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
        UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
        guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
        self.layer.render(in: pdfContext)
        UIGraphicsEndPDFContext()
        return self.saveViewPdf(data: pdfData)

    }

2      

Can you explain what you're trying to accomplish in more details? My understanding is you have a view placed inside a UIScrollView, as it likely higher than the display size so you need to scroll to see all the content, and you want to make a PDF of the scrollview. What is self in this example? If it is the UIScrollView, you shouldn't use the bounds, contentSize is what you're interested in.

2      

I am actually attempting to render the pdf from a UISrollview, I am still having a big fight trying to make it work and I don't know where else to research. The documentation is limited.

3      

I am new to SwiftUI. I am converting a scrollable SwiftUI view to pdf but unable to do that. The output will be empty.

Here is my code

This is the view that I want to convert into pdf

GeometryReader{geo in
                                        FirstView(getResumeId: self.getResumeId).onAppear{
                                            self.exportToPDF(widht:geo.size.width,height:geo.size.height)
                               }
                          }

This is my function that generates the pdf from view

func exportToPDF(width:CGFloat, height:CGFloat) {
        let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let outputFileURL = documentDirectory.appendingPathComponent("\(self.getResumeId).pdf")
        //Normal with
        let width: CGFloat = width
        //Estimate the height of your view
        let height: CGFloat = height
        let charts = FirstView(getResumeId: self.getResumeId)
        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: width, height: height))
        DispatchQueue.main.async {
            do {
                try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
                    context.beginPage()
                    rootVC?.view.layer.render(in: context.cgContext)
                })
                UserDefaults.standard.set(outputFileURL, forKey: "pdf")
                UserDefaults.standard.synchronize()
                print("wrote file to: \(outputFileURL.path)")
            } catch {
                print("Could not create PDF file: \(error.localizedDescription)")
            }

        pdfVC.removeFromParent()
        pdfVC.view.removeFromSuperview()
    }
}

The empty pdf generate or sometimes pdf did not open. I searched alot but unable to do that. If anyone help me I am verythankful to him.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.