Skip to content

Using fonttype 42 will make the produced PDF size considerably larger when the image has Chinese characters #11303

Closed

Description

@jdhao

Description

I want to produce a pdf format image to include in my LaTeX document. The image contains some Chinese characters. I have found that using Chinese characters with fonttype 42 will produce pdf files with greater file size.

The code to reproduce is

import matplotlib.font_manager as mfm
import matplotlib.pyplot as plt
import matplotlib as mpl

font_path = "C:/Windows/fonts/simhei.ttf"
prop = mfm.FontProperties(fname=font_path)
mpl.rcParams['pdf.fonttype'] = 42

ch = False
fig, ax = plt.subplots()

if ch:
	ax.text(0.5, 0.5, "你好", transform=ax.transAxes, fontproperties=prop,
		fontsize=30)
else:
	ax.text(0.5, 0.5, "hello", transform=ax.transAxes, fontsize=30)

plt.savefig("mpl_use_ch.pdf", bbox_inches='tight')
plt.show()

If I set ch=True, the size of produced pdf is 5327k. Otherwise, the size of produced pdf is 374k.

When I comment out the line mpl.rcParams['pdf.fonttype'] = 42, then the produced pdf size is more or less the same no matter I use ch=True or ch=False.

Is this the expected behaviour? Why does using fonttype 42 make the produce pdf size so large?

Versions

  • Operating system: Windows 10
  • Matplotlib version: 2.1.2
  • Python version: 3.6.4

The matplotlib package is installed using conda.

Activity

  1. jklymak commented on May 24, 2018

    @jklymak
    Member

    I'd assume one font set is much larger than the other, and/or its included in Type-3 fonts, but not in TrueType (42)?

  2. jdhao commented on May 24, 2018

    @jdhao
    Author

    Use fonttype 42 and ch=True

    The size of the produced pdf is 5327k. If I use pdffonts to check the pdf file, the output is:

    name                                 type              encoding         emb sub uni object ID
    ------------------------------------ ----------------- ---------------- --- --- --- ---------
    DejaVuSans                           CID TrueType      Identity-H       yes no  yes     23  0
    SimHei                               CID TrueType      Identity-H       yes no  yes     14  0
    

    Use fonttype 42 and ch=False

    The size of the produced pdf is 374k. The output of pdffonts command is

    name                                 type              encoding         emb sub uni object ID
    ------------------------------------ ----------------- ---------------- --- --- --- ---------
    DejaVuSans                           CID TrueType      Identity-H       yes no  yes     14  0
    

    comment out the line about fonttype and ch=True

    The pdf file size is 9k. Output of pdffonts command is:

    name                                 type              encoding         emb sub uni object ID
    ------------------------------------ ----------------- ---------------- --- --- --- ---------
    DejaVuSans                           Type 3            Custom           yes no  no      20  0
    SimHei                               Type 3            Custom           yes no  no      14  0
    

    comment out the line about fonttype and ch=False

    The pdf file size is 7k. Output of pdffonts command is:

    name                                 type              encoding         emb sub uni object ID
    ------------------------------------ ----------------- ---------------- --- --- --- ---------
    DejaVuSans                           Type 3            Custom           yes no  no      14  0
    

    some obsevervations

    It seems that the quality of the produced pdf is not degraded if we comment out the line about fonttype. Although the fonttype is now Type 3, but the generated pdf will not lose any detail if I
    zoom in the pdf files (see the image below for an example).

    image

    So is it safe to use Type 3 font? What is the difference does it make to use fonttype 42? It seems that option only increases the file size but do not produce pdf with better display quality.

  3. jklymak commented on May 24, 2018

    @jklymak
    Member

    I think "safe" is relative - if you need to edit the glyphs in graphics package like Illustrator then I think you want type 42 fonts. There may also be compatibility issues if a downstream viewer doesn't have SimHei for some reason? ping @anntzer @jkseppan who grok this stuff...

  4. anntzer commented on May 24, 2018

    @anntzer
    Contributor

    Per comment in backend_pdf.py:

        def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
            # TODO: combine consecutive texts into one BT/ET delimited section
    
            # This function is rather complex, since there is no way to
            # access characters of a Type 3 font with codes > 255.  (Type
            # 3 fonts can not have a CIDMap).  Therefore, we break the
            # string into chunks, where each chunk contains exclusively
            # 1-byte or exclusively 2-byte characters, and output each
            # chunk a separate command.  1-byte characters use the regular
            # text show command (Tj), whereas 2-byte characters use the
            # use XObject command (Do).  If using Type 42 fonts, all of
            # this complication is avoided, but of course, those fonts can
            # not be subsetted.
    

    Note in particular the last three lines: type 42 fonts cannot be subsetted, i.e. you're getting the full font.
    Actually that's likely not true (unclear?) (I think TrueType can likely be subsetted), it's just not implemented (and likely very complex to do unless we bring in an extra dependency such as https://github.com/fonttools/fonttools).

    Type 3 fonts don't support hinting, which is important (typically) for better displaying very small font sizes.

    Tempted to close as can't fix.

  5. jdhao commented on May 25, 2018

    @jdhao
    Author

    I do not want to edit this pdf file in illustrator or something. I just want to include it in my LaTeX document. Is it safe to use type 3 font? As my document contains a lot of figures, it will become very large if I choose to use type 42 font.

  6. anntzer commented on May 25, 2018

    @anntzer
    Contributor

    Why don't you try it?
    (I guess this suggests there should be a way to not embed the font at all and let LaTeX take care of it.)

  7. jdhao commented on May 25, 2018

    @jdhao
    Author

    Right now, I just use the type 3 font. The quality of the figure is fine. The only thing that worries me is that
    some publisher do not accept type 3 font.

  8. jklymak commented on May 25, 2018

    @jklymak
    Member

    Closing as "won't fix".

    I've never heard of a publisher not accepting a type-3 font. But if they do, you can just make the 2-Gb version of your document for them. I'm not sure, but its possible/probable that pdflatex is smart enough to only embed the font once rather than once for each figure... Feel free to continue to comment here, even if its closed... Of if you feel super strongly that this is a huge problem, we can re-open and add to the wishlist...

  9. jkseppan commented on May 25, 2018

    @jkseppan
    Member

    I think I have seen publisher guidelines forbidding type-3 fonts, probably from a time when pdftex embedded bitmap fonts as type-3, before good-quality type-1 versions of the TeX fonts were freely available. Those bitmap fonts were slow to render and increased the file size by a lot.

    Indeed, type-42 font subsetting is not implemented. I think MEP14 would probably address this.

    One further idea: ghostscript can subset fonts and otherwise optimized pdf files. It's always a little difficult to get the flags right, but this stackoverflow answer lists a lot of the flags. Experimenting with some combinations of them could produce a smaller pdf file of good quality. We could in principle add a "distill" step such as the one in the ps backend so we'd offload font subsetting to ghostscript, but I wouldn't want to depend on it, and it's not trivial to get the flags right for all possible versions.

  10. jdhao commented on May 25, 2018

    @jdhao
    Author

    IEEE conference paper submission specifically state that type 3 font should not be used, for example, see here. The pdf file will not pass the pdfexpress check. Often there is also a file size limit. So maybe we will be in a dilemma to meet all the requirements.

  11. jkseppan commented on May 25, 2018

    @jkseppan
    Member
  12. jdhao commented on May 26, 2018

    @jdhao
    Author

    Converting the PDF to Ghostscript file and then convert back to PDF will produce an optimized PDF with much smaller file size. The quality of the optimized PDF is acceptable.

  13. kaigaox commented on Apr 10, 2020

    @kaigaox

    Not sure about how to subset Chinese chars, but for English, you can subset fonts by yourself and then use these fonts in generating pdf files. For example, the following can subset the essential characters from a ttf file:

    #!/usr/bin/env fontforge

    Open($1);
    SelectAll();
    SelectFewer(0ub0);
    SelectFewer(0ub1);
    SelectFewer(0ud7);
    SelectFewer(0uf7);
    SelectFewer(0uf8);
    SelectFewer(0u35e);
    SelectFewer(0u360);
    SelectFewer(0u3d1);
    SelectFewer(0u3d5);
    SelectFewer(0u3d6);
    SelectFewer(0u3dc);
    SelectFewer(0u3dd);
    SelectFewer(0u3f0);
    SelectFewer(0u3f1);
    SelectFewer(0u3f5);
    SelectFewer(0u2da);
    SelectFewer(0u30a);
    SelectFewer(0u391,0u3a9);
    SelectFewer(0u3b1,0u3c9);
    SelectFewer(0u20,0u7e);
    DetachAndRemoveGlyphs();
    Generate($2);
    Quit(0);

    And save as it as, say, ./extract_subset. Then for a ttf file, you can:
    ONTFORGE_LANGUAGE=ff ./extract_subset ./font.ttf ./font_subset.ttf

    Also, you can use this: https://github.com/pts/pdfsizeopt

  14. wookayin commented on Jul 28, 2020

    @wookayin

    Although this won't be fixed, but sharing a note for somebody who might bump into this issue by Googling:

    Please be aware that using fonttype 42 will make your PDF file size pretty big. This is because the PDF file has to embed the fonts being used. For example, a dead simple figure with an empty axis will eat up ~400KB if fonttype 42 is used, whereas the filesize is only ~5KB (which is somewhat reasonable) when fonttype 3 is used; even though any Unicode/Chinese character is not used.

    mpl.rcParams['pdf.fonttype'] = 3   # or 42
    
    fig, ax = plt.subplots(figsize=(4, 3))
    fig.savefig("./test.pdf")
    
  15. tacaswell commented on Jun 23, 2021

    @tacaswell
    Member

    I am going to re-open this because we have work in-flight to sub-set type 42 fonts.

  16. added this to the v3.5.0 milestone on Jul 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions