14
votes

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?

1
Do you draw text on your own in the context? Could you post some code what you do in this method? I see that in the PDFPage exist NSAttributedString attribute string. - Ramis
I don't want to draw anything new on the page, I just want to show existing documents in Night Mode (dark background and light foreground). Kinda like in the Adobe Reader: forums.adobe.com/thread/1837487 - Bedford
Did you ever find a way for applying night mode or inverting colors in your pdfpage? - SleepNot
Our company decided to use another toolkit (Foxit Mobile SDK for iOS), which supports night mode out of the box with a single method call. But as for Apple's SDK: no, I still don't know how to achieve the same. - Bedford

1 Answers

7
votes

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));