2013-04-16 6 views
6

Ho uno UITableView che è popolato con alcuni dati ma poiché contiene dati che sono più celle dell'area visualizzabile dello schermo, sono riuscito a ottenere solo l'istantanea di esso, voglio sapere se c'è qualche altro modo per ottenere l'intero snapshot Tableview in pdf..this è quello che ho provato grazieCome ottenere un'istantanea di UITableView in un formato PDF

- (IBAction)clickMe:(id)sender 
{ 
    UIView *viewToRender = self.myTableView; 
    CGPoint contentOffset = self.myTableView.contentOffset; 

    UIGraphicsBeginImageContext(viewToRender.bounds.size); 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 

    // KEY: need to translate the context down to the current visible portion of the tablview 
    CGContextTranslateCTM(ctx, 0, -contentOffset.y); 

    [viewToRender.layer renderInContext:ctx]; 

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIImageView *myImage=[[UIImageView alloc]initWithImage:image]; 

    UIGraphicsEndImageContext(); 

    [self createPDFfromUIViews:myImage saveToDocumentsWithFileName:@"PDF Name"]; 

} 



- (void)createPDFfromUIViews:(UIView *)myImage saveToDocumentsWithFileName:(NSString *)string 
{ 
    NSMutableData *pdfData = [NSMutableData data]; 

    UIGraphicsBeginPDFContextToData(pdfData, myImage.bounds, nil); 
    UIGraphicsBeginPDFPage(); 
    CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData 

    [myImage.layer renderInContext:pdfContext]; 

    // remove PDF rendering context 
    UIGraphicsEndPDFContext(); 
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); 

    NSString* documentDirectory = [documentDirectories objectAtIndex:0]; 
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:string]; 

    NSLog(@"%@",documentDirectoryFilename); 
    [pdfData writeToFile:documentDirectoryFilename atomically:YES]; 
} 

risposta

14
UIGraphicsBeginImageContext(self.myTableView.contentSize); 
[self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; 
[self.myTableView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

int rows = [self.myTableView numberOfRowsInSection:0]; 
int numberofRowsInView = 4; 
for (int i =0; i < rows/numberofRowsInView; i++) { 
    [self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(i+1)*numberofRowsInView inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; 
    [self.myTableView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

} 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIImageView *myImage=[[UIImageView alloc]initWithImage:image]; 
UIGraphicsEndImageContext(); 


[self createPDFfromUIViews:myImage saveToDocumentsWithFileName:@"PDF Name"]; 

non so, ma questo codice funziona come un fascino per me ..

+1

Nizza! Non lo sapevo, dovresti accettare la tua risposta, – Jano

+1

Ciao, grazie per questo codice. Ho faticato a farlo. Non sono sicuro di cosa sto sbagliando. Ho usato questo codice ma non sembra funzionare dopo aver scrollato tableview. Potete per favore controllare la mia domanda e dare i vostri pensieri per favore -http: //stackoverflow.com/questions/17771112/ios-rendering-uitableview-into-pdf Sarebbe davvero grato. – applefreak

+0

Grazie, davvero utile, inoltre, non dimenticare che UITableView è stato ereditato da UIScrollView, quindi è possibile farlo: CGFloat screensInTable = self.tableView.contentSize.height/self.tableView.frame.size.height; per (int i = 1; i

2

non ci sono le cellule fuori campo perché sono riciclati appena scorrere fuori dallo schermo visibile. Invece di fare lo screenshot di UITableView, dovresti prendere in considerazione la creazione di una versione PDF usando Core Text. Forse puoi adattare questo example.

+0

grazie per l'information..i ottenuto un piccolo pezzo di codice che mi aiuta a fare il processo di snapshot, date un'occhiata al mio codice – vin

1

in base alla risposta di Vin (può anche essere utilizzato per snapshotting UIScrollViews):

UIGraphicsBeginPDFContextToData(pdfData, CGRectMakeWithSize(0, 0, self.productsTable.contentSize), nil); 
    UIGraphicsBeginPDFPage(); 
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    [self.productsTable scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; 
    [self.productsTable.layer renderInContext:UIGraphicsGetCurrentContext()]; 

    CGFloat screensInTable = self.productsTable.contentSize.height/self.productsTable.height; 

    for (int i = 1; i < screensInTable; i++) { 
     CGPoint contentOffset = CGPointMake(0, i * self.productsTable.height); 
     [self.productsTable setContentOffset:contentOffset animated:NO]; 
     [self.productsTable.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    } 

    UIGraphicsEndPDFContext(); 
3

Ecco come si può fallo senza scorrere la vista tabella. Semplicemente aumenta l'altezza della scrollview fino a contentSize. La qualità del PDF è anche migliore se non vai via UIImage. Questo è dal mio interno UITableView in Swift. Il codice viene rubato da qui e là quindi i commenti non sono sempre miei.

func toPDF(fileName: String) -> String { 
    // Don't include scroll indicators in file 
    self.showsVerticalScrollIndicator = false 

    // Creates a mutable data object for updating with binary data, like a byte array 
    let pdfData = NSMutableData() 

    // Change the frame size to include all data 
    let originalFrame = self.frame 
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.contentSize.width, self.contentSize.height) 

    // Points the pdf converter to the mutable data object and to the UIView to be converted 
    UIGraphicsBeginPDFContextToData(pdfData, self.bounds, nil) 
    UIGraphicsBeginPDFPage() 
    let pdfContext = UIGraphicsGetCurrentContext(); 

    // Draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData 
    self.layer.renderInContext(pdfContext!) 

    // Remove PDF rendering context 
    UIGraphicsEndPDFContext() 

    // Retrieves the document directories from the iOS device 
    let documentDirectories: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 

    let documentDirectory = documentDirectories.objectAtIndex(0) 
    let documentDirectoryFilename = documentDirectory.stringByAppendingPathComponent(fileName); 

    // Instructs the mutable data object to write its context to a file on disk 
    pdfData.writeToFile(documentDirectoryFilename, atomically: true) 

    // Back to normal size 
    self.frame = originalFrame 

    // Put back the scroll indicator 
    self.showsVerticalScrollIndicator = true 

    return documentDirectoryFilename 
} 
+0

Sembra funzionare, ma quando lo faccio, aggancia 1 e mezza fila sopra e sotto – vinbhai4u

0

Penso che tutti si dimentica che è un UITableViewUIScrollView dopo tutto. Non è necessario calcolare celle, altezza, ecc. È sufficiente creare il contesto con contentSize, impostare tableView.frame.size = tableView.contentSize e renderlo nel contesto.

Si prega di vedere questo esempio

 UIGraphicsBeginImageContext(tableView.contentSize) 
     let context = UIGraphicsGetCurrentContext() 

     let cachedOffset = CGPoint(x:tableView.contentOffset.x , y:tableView.contentOffset.y) 
     let cachedFrame = tableView.frame 

     tableView.contentOffset = .zero 
     tableView.frame = CGRect(x: 0, y: 0, width: tableView.contentSize.width, height: tableView.contentSize.height) 
     tableView.layer.render(in: context) 

     tableView.frame = cachedFrame 
     tableView.contentOffset = cachedOffset 

     if let image = UIGraphicsGetImageFromCurrentImageContext() { 
      let imageView = UIImageView(image: image) 
      self.createPDF(fromUIViews:myImage saveToDocumentsWithFileName:"PDF Name") 
     } 

     UIGraphicsEndImageContext()