使用Apple的PDFKit框架更改文本和背景颜色

Bed*_*ord 12 pdf macos objective-c ios swift

我想使用Apple的PDFKit框架更改显示的PDF文档的文本和背景颜色,以"夜间模式"显示文档(深色背景,浅色前景,就像在Adobe Reader中一样).

我知道PDFPage类有一个drawWithBox:toContext:方法,可以在子类中覆盖以添加效果(如水印,如本WWDC 2017会话中所示),但我不知道如何设置颜色属性.

有没有办法用PDFKit库或Apple的任何其他低级API(Quartz)来做到这一点?

Bal*_*ali 8

为了给出PDF格式的文字颜色,你可以使用,

-(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;
}
Run Code Online (Sandbox Code Playgroud)

对于背景颜色,请使用以下颜色

CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor );
    CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));
Run Code Online (Sandbox Code Playgroud)

  • 该方法应该放在哪里,谁调用它? (3认同)