Swift Save UITextView Text to .Pdf, .Doc and .Txt file formate and Display

Viewed 1143

My Scenario, I am trying to save UITextView Text with Three format .pdf, .doc and .txt. Here, formate option user can choose based on alert option. Once Its saved need to show in Preview controller for file sharing. How to achieve this?

func createPDF(text:String, filename:String) {

        // 1. Create Print Formatter with input text.
        let formatter = UIMarkupTextPrintFormatter(markupText: text)

        // 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
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        pdfData.write(toFile: "\(documentsPath)/\(filename).pdf", atomically: true)
        print("saved success:\(documentsPath)\(filename)")
        listFiles()
    }
2 Answers

Try the following code :)

let txtData = Data(textView.txt.utf8)
do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = (documentsPath as NSString).appendingPathComponent("\(filename).pdf")
        let url = URL(fileURLWithPath: filePath)
        // pdfData created by your code above
        // txtData for ".txt"
        pdfData.write(to: url)

        let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)

        // Use your desired viewController here, or just use the rootViewController
        UIApplication.shared.keyWindow?.rootViewController?.presentViewController(activityVC, animated: true, completion: nil)
    } catch (let error) {
        print("\(error)")
    }
Related