Rakesh Thummar
Rakesh Thummar

Reputation: 197

How to draw a table in a PDF file in iOS.

Currently I am developing an Expense Management App. In this app, I want retrive data from the local database and make a pdf file for it in a tabular format.Guidance needed on how should I proceed on doing this.

Thanks.

Upvotes: 3

Views: 1775

Answers (2)

Nitesh Borad
Nitesh Borad

Reputation: 4663

You can create table in PDF by following below steps:

Step 1. Create UIGraphics PDF Context:

UIGraphicsBeginPDFContextToFile(filePath, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kPageWidth, kPageHeight), nil);
[self drawTableAt:CGPointMake(6,38) withRowHeight:30 andColumnWidth:120 andRowCount:kRowsPerPage andColumnCount:5];
UIGraphicsEndPDFContext();

Step 2. Add these two helper functions to the same file (or same class implementation):

-(void)drawTableAt: (CGPoint)origin  withRowHeight: (int)rowHeight  andColumnWidth: (int)columnWidth  andRowCount: (int)numberOfRows  andColumnCount:(int)numberOfColumns{

    for (int i = 0; i <= numberOfRows; i++) {
        int newOrigin = origin.y + (rowHeight*i);
        CGPoint from = CGPointMake(origin.x, newOrigin);
        CGPoint to = CGPointMake(origin.x + (numberOfColumns*columnWidth), newOrigin);
        [self drawLineFromPoint:from toPoint:to];
    }

    for (int i = 0; i <= numberOfColumns; i++) {
        int newOrigin;
        if(i==0){
            newOrigin = origin.x ;
        }
        if(i==1){
            newOrigin = origin.x + 30;
        }
        if(i==2){
            newOrigin = origin.x + 150;
        }
        if(i==3){
            newOrigin = origin.x + 270;
        }
        if(i==4){
            newOrigin = origin.x + 480;
        }
//        newOrigin = origin.x + (columnWidth*i);
        CGPoint from = CGPointMake(newOrigin, origin.y);
        CGPoint to = CGPointMake(newOrigin, origin.y +(numberOfRows*rowHeight));
        [self drawLineFromPoint:from toPoint:to];
    }
}

-(void)drawLineFromPoint:(CGPoint)from toPoint:(CGPoint)to
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[] = {0.2, 0.2, 0.2, 0.3};
    CGColorRef color = CGColorCreate(colorspace, components);

    CGContextSetStrokeColorWithColor(context, color);
    CGContextMoveToPoint(context, from.x, from.y);
    CGContextAddLineToPoint(context, to.x, to.y);

    CGContextStrokePath(context);
    CGColorSpaceRelease(colorspace);
    CGColorRelease(color);
}

Upvotes: 3

Related Questions