Toto
Toto

Reputation: 7

Is there a way to get a pdf that is generated and saved from document directory to ibooks or to email?

I'm trying to open a pdf file that was generated from a UItableView and display it in iBooks.

I've used the following code

extension UITableView {

    // Export pdf from UITableView and save pdf in drectory and return pdf file path
    func exportAsPdfFromTable() -> String {

        let originalBounds = self.bounds
        self.bounds = CGRect(x:originalBounds.origin.x, y: originalBounds.origin.y, width: self.contentSize.width, height: self.contentSize.height)
        let pdfPageFrame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.contentSize.height)

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

    }

    // Save pdf file in document directory
    func saveTablePdf(data: NSMutableData) -> String {

        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let docDirectoryPath = paths[0]
        let pdfPath = docDirectoryPath.appendingPathComponent("tablePdf.pdf")
        if data.write(to: pdfPath, atomically: true) {
            return pdfPath.path

        } else {
            return ""
        }
    }



}

then I call the function from a button with an IBAction and tried to use the document directory's file path but it doesn't work.

@IBAction func export() {
        let pdfFilePath = self.tableView.exportAsPdfFromTable()
        print(pdfFilePath)

        if let url = URL(string:"itms-books://var/mobile/Containers/Data/Application/3FF01C35-270E-49A0-88DD-E88175A93FCC/Documents/tablePdf.pdf") {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:])
            }
        }
    }

the pdf file is saved in the simulators document directory, is there a way to save it locally in the tablet? what is the best way to get the pdf opened in ibooks?

Upvotes: 0

Views: 134

Answers (2)

Toto
Toto

Reputation: 7

Rather than using the pdf from my document directory, I passed the data on by using the UIActivityViewController to store information that can be copied.

let activityViewController :  UIActivityViewController

           if let personaImage = self.personas[indexPath.row].image, let imageToShare = UIImage(data: personaImage as Data){
               //in swift if lets are used to  se if an opional has a value or not
               activityViewController = UIActivityViewController(activityItems: ["With personia I am sharing my persona named " + self.personas[indexPath.row].name!, imageToShare, "Project name: " + self.personas[indexPath.row].projectName!, "Age: " + self.personas[indexPath.row].age!, "Location: " + self.personas[indexPath.row].location!, "Gender: " + self.personas[indexPath.row].gender!, "Disabilities: " + self.personas[indexPath.row].disability!, "Occupation: " + self.personas[indexPath.row].occupation!, "Bio: " + self.personas[indexPath.row].bio!, "goals: " + self.personas[indexPath.row].goals!, "Motivation One: " + self.personas[indexPath.row].motivation!, "Motivation Two: " + self.personas[indexPath.row].motivationTwo!, "Motivation Three: " + self.personas[indexPath.row].motivationThree!, "Frustration One: " + self.personas[indexPath.row].frustration!, "Frustration Two: " + self.personas[indexPath.row].frustrationTwo!, "Frustration Three: " + self.personas[indexPath.row].frustrationThree!], applicationActivities: nil)
           } else {
               activityViewController = UIActivityViewController(activityItems: ["With personia I am sharing my persona named " + self.personas[indexPath.row].name!], applicationActivities: nil)
           }

           self.present(activityViewController, animated: true, completion: nil)
           if let popOver = activityViewController.popoverPresentationController {
               popOver.sourceView = self.view
           }


       }

Upvotes: 0

Josh Homann
Josh Homann

Reputation: 16347

Here is an example.

import UIKit

class ViewController: UIViewController {
    private static let filename = "myfile.pdf"
    private var documentInteractionController: UIDocumentInteractionController?
    override func viewDidLoad() {
        super.viewDidLoad()
        let pdfData = UIGraphicsPDFRenderer(bounds: .init(origin: .zero, size: .init(width: 400, height: 400))).pdfData { context in
            context.beginPage()
            let attributes = [
                NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 150)
            ]
            let text = "Hello!" as NSString
            text.draw(in: CGRect(x: 0, y: 0, width: 500, height: 200), withAttributes: attributes)
        }
        if let url = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
            let pdfURL = url.appendingPathComponent(ViewController.filename)
            try? pdfData.write(to: pdfURL)
        }
    }

    @IBAction func tapShareButton(_ sender: UIButton) {
        if let url = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
            let pdfURL = url.appendingPathComponent(ViewController.filename)
            documentInteractionController = UIDocumentInteractionController(url: pdfURL)
            documentInteractionController?.presentOpenInMenu(from: sender.frame, in: view, animated: true)
        }
    }
}

Upvotes: 1

Related Questions