5

My application has a tableview with custom cells(include textfield, label and button), I wanna generate a pdf file from the tableview.

Bellow is the code(now assume the tableview's content is all visible):

    UIGraphicsBeginImageContext(self._tableView.bounds.size);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, self._tableView.bounds.size.width, self._tableView.bounds.size.height), nil);

    // what's the code here?
    // [self._tableView drawInRect:];

    UIGraphicsEndPDFContext();

I always generate an blank pdf file. Currently what I do is to generate the tableview as a image, then draw the image to the current context, then will get the pdf file. but any nice idea?

ZYiOS
  • 5,204
  • 3
  • 39
  • 45

2 Answers2

5

HI , you can convert current view as image through the follwoing code and then you have to use that image to create PDF File through the link

    - (UIImage *)captureView:(UIView *)view {
    CGRect screenRect = [[UIScreen mainScreen] bounds];

    UIGraphicsBeginImageContext(screenRect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);

    [view.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
   }
Community
  • 1
  • 1
  • This is the sort of thing I like so much about Cocoa & CoreGraphics -- The primatives and higher level operations and types mesh together very nicely. I never really appreciated stateful graphics systems (i.e. postscript) until doing some serious UIView subclassing. – Armentage Apr 20 '11 at 04:28
  • Thanks, I get this working, but I wanna if the tableview's content is larger than the tableview, how to capture the whole tableview? – ZYiOS Apr 21 '11 at 01:25
  • Dio,if it is working,please tick answer and give upvote..it will help to others.. –  Apr 21 '11 at 04:34
  • Yes,,, You are right for when table height is below 480 in iphone and 1024 ipad but what about when its size is more than 480 for iphone and more than 1024 for ipad...here i dont consider navigation bar and tab bar in frame of table.. – Ashvin Jul 28 '12 at 13:43
  • We can only generate the visible rects of UItableview. – ZYiOS Aug 09 '12 at 06:16
  • Is there any way to take the full tableview? – jcesarmobile Sep 06 '12 at 08:24
  • I haven't tried this, but you could create a clone tableview, offscreen, with the same datasource, and set the bounds to be tall enough to include all the rows. Then run the above code. Of course, this presumes that the tableview and its cells, can all exist simultaneously without memory issues. – mahboudz Dec 14 '12 at 09:58
-1

To get good quality image,

Use

UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0) 

instead of

UIGraphicsBeginImageContext(screenRect.size)

@JeffWood: thank a million, for your answer :)

MarmiK
  • 5,639
  • 6
  • 40
  • 49