use function mutiple pages pdf version of tableview, pass tableview name function :-
func pdfdatawithtableview(tableview: uitableview) { let priorbounds = tableview.bounds let fittedsize = tableview.sizethatfits(cgsizemake(priorbounds.size.width, tableview.contentsize.height)) tableview.bounds = cgrectmake(0, 0, fittedsize.width, fittedsize.height) let pdfpagebounds = cgrectmake(0, 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(), 0, -pageoriginy) tableview.layer.renderincontext(uigraphicsgetcurrentcontext()!) cgcontextrestoregstate(uigraphicsgetcurrentcontext()) pageoriginy += pdfpagebounds.size.height } uigraphicsendpdfcontext() tableview.bounds = priorbounds var docurl = (nsfilemanager.defaultmanager().urlsfordirectory(.documentdirectory, indomains: .userdomainmask)).last! nsurl docurl = docurl.urlbyappendingpathcomponent( "mydocument.pdf") pdfdata.writetourl(docurl, atomically: true) }
update 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, y:0, width:tableview.frame.width, height:self.view.frame.height) let pdfdata = nsmutabledata() uigraphicsbeginpdfcontexttodata(pdfdata, pdfpagebounds,nil) var pageoriginy: cgfloat = 0 while pageoriginy < fittedsize.height { uigraphicsbeginpdfpagewithinfo(pdfpagebounds, 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! url docurl = docurl.appendingpathcomponent("mydocument.pdf") pdfdata.write(to: docurl url, atomically: true) }
Comments
Post a Comment