I can happily use jspdf to add fonts to a pdf. For that so far I add a font for regular, one for italic, one for bold and one for bolditalic in my case.
Now I have some fonts that do not provide these different fonts but variable ttf-fonts and I struggle to use those with JSPDF.
So far my solution goes like this:
pdf.addFileToVFS(`${fontFamily}-bold.ttf`, fontBase64Data);
pdf.addFont(`${fontFamily.ttf}-bold.ttf, fontFamily, 'bold', 700);
where I read fontBase64 data from file (which works nicely for regaulr, italic etc) and do the same with the regular and italic fonts...
For variable fonts I tried to add a font with variable font weight with above code just use the fontBase64Data as I read it from the ttf file of variable font.
However that just leaves the font regular.
To my understanding that alos makes sense as the API of addFonts seems to associate a loaded font with a font weight it represents, but does not seem to apply a font weight to the font.
Since I want to use variable fonts however I seem to need to either
set a font as variable font, so weight would be automatically applied
apply a weight to the variable font via api and then define that as bold
So far I couldn't find any of that. Am I missing sth or are variable font weights currently not supported yet by jspdf?
Cheers
Tom
First of all, there are many questions on StackOverflow, but none that fully answer this question.
The problem is mainly, but most likely not limited to, Thai and Arabic diacritics when rendered with a custom Latin-only font, using the text property of a UILabel. Which is also intrinsically sized in an auto-layout. I've already done everything Apple suggests, playing with the settings mentioned in their documentation, WWDC videos, as well as questions on StackOverflow (e.g. clipsToBounds = NO, etc.). Keep in mind, only my custom font setup clips in my scenario, not the iOS system font (.SF-UIDisplay), and not even the iOS system provided Helvetica or Helvetic Neue. The custom font has been checked and rechecked, and at this point the conclusion, iOS is the anomaly across all platforms, even macOS. To be even clearer, the same clipping behavior as the custom font can be seen with SF Pro, a font provided by Apple themselves here: https://developer.apple.com/fonts/
This question is about the most proper, least intrusive, and most complete way to do what is necessary to not clip diacritics. Meaning, how would you do this, ideally, from scratch.
All of my font research and test runs have led all those involved in this problem to believe that Apple has implemented special treatment specifically for their system fonts in UILabel, to avoid diacritic clipping. So making that an assumption, I'm also assuming the font is ok, and I'm looking for solutions that do not involve editing the font.
In my tries to use the font, the first thing to go wrong was vertical clipping of the ascender diacritics of Thai glyphs:
นื้ทั้มูHello
This means the glyphs of the font Thonburi when they cascade from the custom Latin-only font. The fix from this point, was to use a custom font only for Thai without any Latin characters, so it could be defined as the primary font, and cascade to the previously mentioned Latin-only custom font. After all this, the custom Thai font still has horizontal clipping issues on diacritics that come at the end of the text:
Worldฟล์
So now I am at a loss for anything further that font management puppetry can do (though still open to suggestions), and I am moving on to more code-centric fixes. I've seen quite a few questions and answers mentioning subclassing UILabel, but I'd like to know what this would look like that could accomplish what I've described.
I'd also like to know if just opting out of UILabel would be an option for anyone. Meaning would writing something from the ground up with TextKit be worth it to avoid all these bugs that seem to only plague iOS, and specifically UILabel.
At first I thought this was a problem with the framework but it's not, it's just a strict enforcement of a font's metrics. And in probably everything but web/app development, fonts are not rendered so strictly, which is why this problem rarely comes up. Fonts have a number of metrics that tell the program rendering it onto the screen how to render it, most importantly how to handle padding. And UILabel (and UITextField, and likely others) applies these metrics strictly. And the problem for us is that some fonts are very decorative and are often too thick or oblique to fit perfectly into the square canvas that each character must fit into (this is especially the case with accents, like umlauts). This isn't a problem outside of web/app development because when a character doesn't fit into its canvas, like a very thick, wide, and oblique W, the program just shows it anyway, and that's why a low-hanging g might spill into the line below it. But if that g was rendered in a single-line UILabel, because of how strict the font-metric enforcement is in iOS, that low-handing g is clipped.
Subclassing UILabel (in the case of UILabel) and overriding its intrinsicContentSize to add some extra padding is not a good idea, on further research. For one, it's kind of hacky, but more importantly, it produces constraint warnings in the debugger. The true fix, and the only acceptable fix AFAIK, is to edit the font's metrics.
Download a program like Glyphs (https://glyphsapp.com/), open the font, open the Font's Info, and in the Masters tab, give the font the proper ascender and descender values. To best understand how these values work, open the San Francisco font in the program and see how Apple did it (it's the font they made specifically for macOS and iOS development). As a side note, if you use this app, when you're editing the font's info, go into the Features tab as well, delete all of the features (using the minus icon in the lower left) and hit Update to let the program manage the font's features for you.
The last hurdle is clipping at the leading edge (not the top and bottom) which the ascender and descender metrics don't address. You can use the Glyphs program to edit the canvas size of individual characters to make sure they all fit but that changes the complexion of the font because it changes the character spacing too noticeably. For this problem, I think the best solution is to simply use attributed strings for your labels and text fields. And that's because attributed strings let you safely edit padding without hacking into intrinsic sizes. An example:
someLabel.attributedText = NSAttributedString(string: "Done", attributes: [NSAttributedString.Key.font: UIFont.blackItalic(size: 26), NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.paragraphStyle: NSMutableParagraphStyle.kItalicCenter])
For convenience, I extended NSMutableParagraphStyle since I use this font all over:
extension NSMutableParagraphStyle {
static var kItalicCenter: NSMutableParagraphStyle {
let s = NSMutableParagraphStyle()
s.alignment = .center
s.firstLineHeadIndent = 2
s.headIndent = 2
return s
}
}
This label will push the font forward a couple of points to prevent clipping.
I was trying to solve similar problem with diacritics in Arabic and found workaround:
I have a UITableViewCell with UILabel with arabic text, it's diacritics were cut sometimes
I overrided - (void)drawRect:(CGRect)frame to directly draw NSAttributedString on UITableViewCell
Also I decreased alpha self.arabicLabel.alpha = 0.1; to draw manually on top of label position, I still keep it to calculate cell's height
- (void)drawRect:(CGRect)frame {
[super drawRect:frame];
if (self.viewModel == nil) return;
NSAttributedString *string = [self.viewModel arabicStringWithTajweed];
CGRect originalRect = [self convertRect:self.arabicLabel.frame fromView:self.arabicLabel];
[string drawInRect:originalRect];
}
The core problem on iOS is font substitution. You are specifying a latin font, the font does not contain glyphs for the characters that will be rendered, the system uses a different font to draw the glyphs, but it is still measuring based on the original font.
Option 1, the most robust option, is to manually choose fonts that include glyphs for the characters you will render. When the font assigned to UILabel, or the attributed string it is rendering, contains all the glyphs that will be rendered, and that font has good metrics as most system fonts do, then nothing will be clipped.
Option 2, manually measure the string using glyph bounds. Make a subclass of UILabel and override textRectForBounds and possibly drawText. Measure the string with .usesDeviceMetrics. This is slower that measuring by font metrics and produces different results. For example, the strings "a" and "A" will measure differently.
Option 3, use baseline offset and line height multiple to make room for the diacritics that are being clipped. Choose or compute constant values for each font for each language, and apply those to the attributed string of the UILabel. This can compensate for the different in font metrics between the font you chose and the font that is actually rendering glyphs. We had localized strings with the worst case clipped characters for each language, and used those to compute the offset and height. Different fonts have different worst case clipping characters.
UIFont provides the +preferredFontForTextStyle: method to get a font instance with the proper size based on the user's selected content size category and the given UIFontTextStyle.
What I would like to do is get a font for a given text style and content size. Something like +fontForContentSizeCategory:andTextStyle:.
Unfortunately I cannot find anything similar to that in the headers for UIFont or UIFontDescriptor.
Any idea on how to achieve this?
Thanks
Unfortunately, both +[UIFont preferredFontForTextStyle:] and +[UIFontDescriptor preferredFontDescriptorWithTextStyle:] rely on -[UIApplication preferredContentSizeCategory] internally. They use a private function _CTFontDescriptorCreateWithTextStyle to retrieve a CoreText font descriptor with specific text style and size category, and that's eventually based on a category → size mapping from the configuration file CoreTextConfig.plist stored somewhere, but I assume you wouldn't want to use private APIs.
While hesitantly implying a possibility to dynamically swizzle -[UIApplication preferredContentSizeCategory] to trick +[UIFontDescriptor preferredFontDescriptorWithTextStyle:] into returning a font descriptor for the size class you want, I can't recommend any specific approach to this. You can retrieve a font descriptor like this:
let descriptor = UIFontDescriptor(fontAttributes: [ UIFontDescriptorTextStyleAttribute : UIFontTextStyleBody ])
but it won't contain a size attribute, so you would be left with trying to come up with a category → size mapping yourself.
Since iOS 10.0 this is possible using UITraitCollection:
let traitCollection = UITraitCollection(preferredContentSizeCategory: contentSizeCategory)
let font = UIFont.preferredFont(forTextStyle: textStyle, compatibleWith: traitCollection)
Is it possible to force a UIFont to be monospaced?
Specifically I'm using a font which does not contain monospaced numbers (tabular numerals). Creating a modified font object which is monospaced and adding that font to the numeric segments of attributed strings would work great.
Another solution may be to add custom attributes to an attributed string and modify what is handling the layout of the text to use a fixed size for glyphs in particular ranges.
Things that Haven't Worked:
There are a number of questions that propose solving similar problems by overriding -drawRect: or -drawTextInRect: on a UILabel (see: Is it possible to alter the letter-spacing/kerning of a font with Cocoa Touch?). This seems like an insane solution and would be prohibitively complex if a string mixes monospaced and not-monospaced fonts.
There are also number of questions which suggest, specifically in regards to numerals, creating a font with a font descriptor with certain font features enabled. (see Displaying proportionally spaced numbers (instead of monospace / tabular) on iOS). This seems only to work in fonts which include these features. The font I'm using does not include these features and they have no effect. The font features can be checked by using something like NSLog(#"%#", CTFontCopyFeatures ( ( __bridge CTFontRef ) myFont ));
I'm trying to reduce the weight of font in UILabel text.
I'm using Helvetica font, still i want the text more thinner.
how can i reduce the thickness of UILabel text font weight?
You can set the font to a different variant in the same family, for instance Helvetica-Light (where by default you get Helvetica-Regular). iosfonts.com provide a nice site for viewing font options.
You can't set an arbitrary weight for any font. Some fonts have a bold and regular variant. A smaller number also have a "light" variant. As the other poster said, if the font is one of those that has a light variant, you can select that, but you can't arbitrarily reduce the weight of a font.
You need to reduce the pointSize of the UIFont used by the UILabel:
UILabel *label; // Your Label
UIFont *font = label.font;
label.font = [font fontWithSize:(font.pointSize - 4)];
This example reduces the font by 4 points.