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



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

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

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

要以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;
}

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

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

最新更新