Search code examples
iosswiftemail-attachments

Attach the pdf file into mail automatically after saving


My app creates pdf file when I hit enter. I want to add one more function to the enter button. The second function is going to attach the created pdf file into mail. So when I hit enter the pdf file will be created and attached into mail.

This code is for saving pdf file:

    @IBAction func EnterButtonAction(_ sender: AnyObject) {

let html = "PDF FILE TITLE"

let fmt = UIMarkupTextPrintFormatter(markupText: html)

// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAt: 0)

// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 1000) // 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 pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)

for i in 1...render.numberOfPages {

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

UIGraphicsEndPDFContext();

// Save PDF file
let path = "\(NSTemporaryDirectory())MyAppFile.pdf"
pdfData.write(toFile: path, atomically: true)
print("open \(path)") // command to open the generated file

}


Solution

  • The Swift 3.0 code below is worked great!

    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)