Search code examples
iospdftextcore-graphicsquartz-2d

How would I invert text color on a pdf rendered with CoreGraphics on iOS?


I am using an open-source PDF viewing library (VFR PDF Reader https://github.com/vfr/Reader). I'm trying to implement "night mode" or black background with white text. I can get the background to any color I like but I can't get the text color to change. You can see where you can modify the background color at https://github.com/vfr/Reader/blob/master/Sources/ReaderContentPage.m in the "drawLayer" method. It is simply changing the color of the rectangle the PDF is rendered on.

My question is: is there something I can do to the "context" that would cause the text in the pdf to change color (in my case I want white text)? The line in question looks like this (line 558):

CGContextDrawPDFPage(context, _PDFPageRef); // Render the PDF page into the context

Solution

  • Here is how I solved the night vision:

    1)I keep track of user preference (night mode or Day mode) in NSUserDefault

    2) in

    - (void)drawLayer:(CATiledLayer *)layer inContext:(CGContextRef)context
    {
    

    a) retrieve the user preference

    NSString *userViewMode = [[NSUserDefaults standardUserDefaults] objectForKey:@"DayOrNightSetting"];
    

    b) set the back ground color of the CGContextRef to white

     CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    

    c) replace CGContextDrawPage(Context,_PDFPageRef) with :

    if ([userViewMode isEqualToString:@"Night"]) {
            CGContextSetBlendMode(context, kCGBlendModeDestinationAtop);
    
            CGContextDrawPDFPage(context, _PDFPageRef);
            CGContextSetBlendMode(context, kCGBlendModeExclusion);
            CGContextDrawPDFPage(context, _PDFPageRef);
        }
        else
        {
           CGContextSetBlendMode(context,kCGBlendModeNormal);
        CGContextDrawPDFPage(context, _PDFPageRef);
        }