在Swift,iOS中将tableView转换为多页PDF的最佳方法之一
发布时间:2020-12-14 04:48:19 所属栏目:百科 来源:网络整理
导读:使用此函数获取多页pdf版本的tableView,只需将tableView名称传递给此函数: – func pdfDataWithTableView(tableView: UITableView) { let priorBounds = tableView.bounds let fittedSize = tableView.sizeThatFits(CGSizeMake(priorBounds.size.width,tabl
使用此函数获取多页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) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |