Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the text and background color with Apple's PDFKit framework

I'd like to change the text and background color of a displayed PDF document using Apple's PDFKit Framework to show the documents in "Night Mode" (dark background, light foreground, just like in Adobe Reader).

I know the PDFPage class has a drawWithBox:toContext: method, which can be overwritten in a subclass to add effects (like watermark, as shown in this WWDC 2017 session), but I don't know how to set the color properties.

Is there a way to do this with the PDFKit library or any other low-level API (Quartz) from Apple?

like image 489
Bedford Avatar asked Jun 10 '17 11:06

Bedford


1 Answers

For giving text color in pdf you can use,

-(CGRect)addText:(NSString*)text withFrame:(CGRect)frame font:(NSString*)fontName fontSize:(float)fontSize andColor:(UIColor*)color{
    const CGFloat *val = CGColorGetComponents(color.CGColor);

    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(currentContext, val[0], val[1], val[2], val[3]);
    UIFont *font =  [UIFont fontWithName:fontName size:fontSize];
    CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:NSLineBreakByWordWrapping];

    CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

    [text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];

    frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

    return frame;
}

And for background color, use the following

CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor );
    CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));
like image 54
Amal T S Avatar answered Nov 12 '22 00:11

Amal T S