Fix cache key collision for fonts with bad TTF metadata #1384
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Steps to reproduce
See the attached test file.
In general:
Have two fonts with bad
fullname
TTF metadata. For example these two both havefullname
"-"
:Use the fonts in pdfkit:
See that all the text is rendered with the first font:
Expected:
Problem
The problem is that
doc.font()
uses the TTFfullname
as the key in_fontFamilies
. And because both fonts have the samefullname
, a cache key conflict happens anddoc.font()
will always load the first font from the_fontFamilies
cache, even when the second font is requested.pdfkit/lib/mixins/fonts.js
Lines 53 to 58 in 3f69586
Solution
The solution is to not use TTF
fullname
as the cache key, when there is another name available -- such as when the font has been registered.So this solution to the bad
fullname
problem works only when the fonts are registered in advance. If we wanted to make it work without pre-registering, then we would need to somehow detect what a badfullname
is (e.g. check thatfullname !== '-'
), but that feels fragile. So I think requiring font registration in this case is acceptable.Refactoring
I've removed the following repeated setting of
_fontFamiliies
to set it only once. I couldn't think of a reason why it would need to be done twice with different cache keys:pdfkit/lib/mixins/fonts.js
Lines 60 to 67 in 3f69586
Then since there is only one cache key now, I've renamed it to
name
.Unit tests
I've added some very simple unit tests. They fail like this before the change:
Checklist