当我按Enter键时,我的应用程序会创建pdf文件。我想在输入按钮上增加一个功能。第二个功能是将创建的pdf文件附加到邮件中。因此,当我按Enter键时,将创建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


}

最佳答案

下面的Swift 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)

关于ios - 保存后自动将pdf文件附加到邮件中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40905525/

10-10 20:35