2016-12-01 105 views
0

當我按回車時,我的應用程序創建pdf文件。我想添加一個更多的功能到輸入按鈕。第二個功能是將創建的pdf文件附加到郵件中。所以當我打入時,pdf文件將被創建並附加到郵件中。保存後自動將pdf文件附加到郵件中

這段代碼保存PDF文件:

@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 

}

+1

http://stackoverflow.com/questions/30423583/attach-a-pdf-file-to-email-swift – Darshana

回答

0

低於雨燕3.0的代碼工作太棒了!

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) 
相關問題