微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Swift,iOS中将tableView转换为多页PDF的最佳方法之一

使用此函数获取多页pdf版本的tableView,只需将tableView名称传递给此函数: –

func pdfDataWithTableView(tableView: UITableView) {


        let priorBounds = tableView.bounds
        let fittedSize = tableView.sizeThatFits(CGSizeMake(priorBounds.size.width,tableView.contentSize.height))
        tableView.bounds = CGRectMake(0,fittedSize.width,fittedSize.height)
        let pdfpageBounds = CGRectMake(0,tableView.frame.width,self.view.frame.height)
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData,pdfpageBounds,nil)
        var pageOriginY: CGFloat = 0
        while pageOriginY < fittedSize.height {
            UIGraphicsBeginpdfpageWithInfo(pdfpageBounds,nil)
            CGContextSaveGState(UIGraphicsGetCurrentContext())
            CGContextTranslateCTM(UIGraphicsGetCurrentContext(),-pageOriginY)
            tableView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
            CGContextRestoreGState(UIGraphicsGetCurrentContext())
            pageOriginY += pdfpageBounds.size.height
        }
        UIGraphicsEndPDFContext()
        tableView.bounds = priorBounds

        var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask)).last! as NSURL
        docURL = docURL.URLByAppendingPathComponent( "myDocument.pdf")
        pdfData.writetoURL(docURL,atomically: true)
    }

解决方法

用swift 3更新

func pdfDataWithTableView(tableView: UITableView) {    
        let priorBounds = tableView.bounds
        let fittedSize = tableView.sizeThatFits(CGSize(width:priorBounds.size.width,height:tableView.contentSize.height))
        tableView.bounds = CGRect(x:0,y:0,width:fittedSize.width,height:fittedSize.height)
        let pdfpageBounds = CGRect(x:0,width:tableView.frame.width,height:self.view.frame.height)    
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData,nil)
            UIGraphicsGetCurrentContext()!.saveGState()
            UIGraphicsGetCurrentContext()!.translateBy(x: 0,y: -pageOriginY)
            tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
            UIGraphicsGetCurrentContext()!.restoreGState()
            pageOriginY += pdfpageBounds.size.height
        }
        UIGraphicsEndPDFContext()
        tableView.bounds = priorBounds
        var docURL = (FileManager.default.urls(for: .documentDirectory,in: .userDomainMask)).last! as URL
        docURL = docURL.appendingPathComponent("myDocument.pdf")
        pdfData.write(to: docURL as URL,atomically: true)
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐