Context: In digging into How can I get Mathematica to not mis-align plot labels when exporting to pdf without rasterizing the text?, and getting an answer to How does pdf export compute the size of the bounding box of Inset?, I have come to discover that PNG export agrees with Mathematica rendering but disagrees with PDF export about the size of text, and that this disagreement is very pronounced for font size 12, but much smaller for font size 16.
I created the following example to demonstrate the disagreement:
ClearAll[NextSize, MakeBound, BoxChars, MakeG];
TextSize[text_] :=
TextSize[text] = Rasterize[Text[text], "RasterSize"];
NextSize[opts___][{_, _, str_},
ch_] := {If[str == "", 0, TextSize[Style[str, opts]][[1]]], ch,
str <> ch};
MakeBound[y_, opts___][{xmin_, ch_, _}] := {EdgeForm[Thin], White,
Rectangle[Offset[{xmin, 0}, {0, y}],
Offset[{xmin, 0} + TextSize[Style[ch, opts]], {0, y}]]};
BoxChars[Style[text_, opts___], y_] :=
Join[Flatten[
Map[MakeBound[y, opts],
Drop[FoldList[NextSize[opts], {0, "", ""}, Characters[text]],1]]],
{Black, Text[Style[text, opts], {0, y}, {-1, -1}]}];
MakeG[nmax_, fs_] :=
Graphics[Flatten[
Table[BoxChars[
Style[StringJoin @@ Table["a", Mod[n, 2, 1]*10], fs],
n/nmax], {n, 1, nmax}]]];
Rasterize[p16 = MakeG[10, 16]]
Rasterize[p12 = MakeG[10, 12]]
Export[FileNameJoin[{NotebookDirectory[], "foo-p16.pdf"}], p16]
Export[FileNameJoin[{NotebookDirectory[], "foo-p16.png"}], p16]
Export[FileNameJoin[{NotebookDirectory[], "foo-p12.pdf"}], p12]
Export[FileNameJoin[{NotebookDirectory[], "foo-p12.png"}], p12]
In Mathematica as well as in PNG export, we get each character in a box:
foo-p12.png
:
foo-p16.png
:
However, in PDF export, the boxes do not align with the characters. At font-size 12, this is quite apparent after 6 or so characters, and by 20 characters, the text fits in only 19 boxes. At font-size 16, it is only barely apparent after 20 characters.
foo-p12.pdf
:
foo-p16.pdf
:
If it's relevant, this is on Mathematica 11.2.0.0 on Windows 10 64-bit.
My question is: What is going on here?
Export
, unfortunately. $\endgroup$Rasterize
in determining the size of anything, especially when it is a text string.Rasterize
is known to be off by 1-2 pixels even in situations when it deals with exact objects. The case of textual primitives is especially painful. $\endgroup$Rasterize[..., "RasterSize"]
withImageDimensions[ImageCrop[Graphics[...]]]
shows a very similar issue; doesImageDiminsions
have the same problem? $\endgroup$