coskukoz
coskukoz

Reputation: 332

Access created pdf file on iPhone

I can create pdf file but I can't find the created file on iPhone device. When I run it on simulator it's possible to find directory where it saved. Where do I have to save it to preview on iPhone?

This is the code for creating pdf file:

func createPDF() {
let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
let fmt = UIMarkupTextPrintFormatter(markupText: html)

// 2. Assign print formatter to UIPrintPageRenderer

let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)

// 3. Assign paperRect and printableRect

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

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

// 4. Create PDF context and draw

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

for i in 1...render.numberOfPages() {

    UIGraphicsBeginPDFPage();
    let bounds = UIGraphicsGetPDFContextBounds()
    render.drawPageAtIndex(i - 1, inRect: bounds)
}

UIGraphicsEndPDFContext();

// 5. Save PDF file

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

pdfData.writeToFile("\(documentsPath)/file.pdf", atomically: true)
}

Upvotes: 1

Views: 131

Answers (2)

Windindi
Windindi

Reputation: 412

Use

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/file.pdf"
    let myRequest = URLRequest(url: URL(fileURLWithPath: documentsPath))
    webView.loadRequest(myRequest)

You can display the contents of the pdf in UIWebView.

Upvotes: 0

Mehul Thakkar
Mehul Thakkar

Reputation: 12592

If you want to preview it, you need to either renter in in your own view in your own app, or otherwise share that pdf to other app, like share it via email, whatsapp, pages app or any other app.

For sharing that pdf, you can use UIActivityViewController.

Here, I am adding code for using the same with objective-c, you can convert it into swift as it is needed.

NSString *pdfFilePath = [documentsPath stringByAppendingPathComponent:@"file.pdf"];
NSURL *URL = [NSURL fileURLWithPath:pdfFilePath];

UIActivityViewController *activityViewController =
[[UIActivityViewController alloc] initWithActivityItems:@[@"My PDF File", URL]
                                  applicationActivities:nil];
[self presentViewController:activityViewController
                   animated:YES
                 completion:^{
                 }];

Swift 3.0 code will be like:

    let pdfFilePath = "path to file.pdf";
    let url = NSURL.fileURL(withPath: pdfFilePath);
    let activityVC = UIActivityViewController(activityItems: ["My Pdf File",url], applicationActivities: nil)
    self.present(activityVC, animated: true, completion: nil);

Upvotes: 1

Related Questions