保存后自动打开pdf文件

时间:2016-12-01 07:42:53

标签: ios swift

当我按下Enter按钮时,我的应用会创建一个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
  }

2 个答案:

答案 0 :(得分:0)

您可以使用PDF打开UIDocumentInteractionController文件,然后找到以下代码:

func showFileWithPath(path: String){
    let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
    if isFileFound == true{
        let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
        viewer.delegate = self
        viewer.presentPreviewAnimated(true)
    }
}

答案 1 :(得分:0)

pdfData.write(toFile: path, atomically: true);是同步调用,因此您可以在此行之后直接编写代码来打开文件,但首先检查文件是否写成功。

var success =  pdfData.write(toFile: path, atomically: true);

if success {
 //Write code to open file in Webview or UIDocumentInteractionController
}