iOS: How to set font when drawing text in pdf generation?

ε祈祈猫儿з 提交于 2019-12-03 16:13:37
itsdamslife

Please try CoreText, a very useful foundation class. Following is the sample code:

CTFontRef font = CTFontCreateWithName((CFStringRef)@"Arial", 16.0f, nil);
CFAttributedStringSetAttribute(textString,CFRangeMake(0, strLength-1), kCTFontAttributeName, font);

Add this to the CFAttributtedStringRef pointer.

This should work.

I think these are what you are looking for

void CGContextSelectFont (
    CGContextRef c,
    const char *name,
    CGFloat size,
    CGTextEncoding textEncoding
);

and

void CGContextSetFontSize (
   CGContextRef c,
   CGFloat size
);

Something like...

CGContextSelectFont(currentContext, "Helvetica", 20, kCGEncodingMacRoman);

or

CGContextSetFontSize ( currentContext, 20);

Hope that helps, here is more... Quartz 2D Programming Guide - Text

Create a CTFont using CTFontCreateWithNameAndOptions (check : CTFont Reference)

Create a mutable attributed string (CFMutableAttributedString Reference) You can edit this mutable string and make any changes you want. In your case, set it's font.

Create your CTFrameSetter with this string and the font should appear.

If you want to be thorough and have enough time, read the String programming Guide

If you want a quick code sample for using CFMutableAttributedString, search CFMutableAttributedString on stackoverflow and most answers will give you an idea of how to use this. For e.g. this question

You can try "libHaru" for generating pdf in iPhone project.

https://github.com/akisute/iPhonePDF

Hope it Helps !!!

What about CGContextSetFont?

NSString *fontName = @"Helvetica";
CGFontRef fontRef = CGFontCreateWithFontName((__bridge CFStringRef)fontName);
CGContextSetFont(context, fontRef);
CGContextSetFontSize(context, 20);

Don't forget to release it:

CGFontRelease(fontRef);

After a lot search, fnd that itsdamslife's answer is correct, but it didn't support for my code.

But, I solved it cheaply. ie, called multiple times the drawText: function to get bold font.

for(int i=0;i<5;i++)
{
 [self drawtext];
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!