Example #1
0
def google_typeface(name):
    try:
        typeface = GOOGLE_TYPEFACES[name]
    except KeyError:
        fonts = google_fonts(name)
        GOOGLE_TYPEFACES[name] = typeface = Typeface(name, *fonts)
    return typeface
from os import path

from rinoh.font import Typeface
from rinoh.font.opentype import OpenTypeFont

__all__ = ['typeface']


def otf(style):
    filename = 'DejaVuSans{}.ttf'.format(style)
    return OpenTypeFont(path.join(path.dirname(__file__), filename))


typeface = Typeface('DejaVu Sans', otf(''), otf('-Oblique'), otf('-Bold'),
                    otf('-ExtraLight'), otf('-BoldOblique'), otf('Condensed'),
                    otf('Condensed-Oblique'), otf('Condensed-Bold'),
                    otf('Condensed-BoldOblique'))
Example #3
0
from os import path

from rinoh.font import Typeface
from rinoh.font.style import REGULAR, BOLD, ITALIC, CONDENSED
from rinoh.font.opentype import OpenTypeFont


__all__ = ['typeface']


def otf(style, variant=''):
    filename = 'texgyreheros{}-{}.otf'.format(variant, style)
    return path.join(path.dirname(__file__), filename)


typeface = Typeface('TeX Gyre Heros',
                    OpenTypeFont(otf('regular'), weight=REGULAR),
                    OpenTypeFont(otf('italic'), weight=REGULAR, slant=ITALIC),
                    OpenTypeFont(otf('bold'), weight=BOLD),
                    OpenTypeFont(otf('bolditalic'), weight=BOLD, slant=ITALIC),
                    OpenTypeFont(otf('regular', 'cn'),
                                 width=CONDENSED, weight=REGULAR),
                    OpenTypeFont(otf('italic', 'cn'),
                                 width=CONDENSED, weight=REGULAR, slant=ITALIC),
                    OpenTypeFont(otf('bold', 'cn'),
                                 width=CONDENSED, weight=BOLD),
                    OpenTypeFont(otf('bolditalic', 'cn'),
                                 width=CONDENSED, weight=BOLD, slant=ITALIC))
from os import path

from rinoh.font import Typeface
from rinoh.font.style import REGULAR, ITALIC, BOLD
from rinoh.font.opentype import OpenTypeFont

__all__ = ['typeface']

# font files were downloaded from https://fontlibrary.org/en/font/carlito


def otf(style):
    filename = 'Carlito-{}.ttf'.format(style)
    return path.join(path.dirname(__file__), filename)


typeface = Typeface('Carlito', OpenTypeFont(otf('Regular'), weight=REGULAR),
                    OpenTypeFont(otf('Italic'), weight=REGULAR, slant=ITALIC),
                    OpenTypeFont(otf('Bold'), weight=BOLD),
                    OpenTypeFont(otf('BoldItalic'), weight=BOLD, slant=ITALIC))
from os import path

from rinoh.font import Typeface
from rinoh.font.style import REGULAR, BOLD, ITALIC, CONDENSED
from rinoh.font.opentype import OpenTypeFont

__all__ = ['typeface']


def otf(style):
    filename = 'DejaVuSerif{}.ttf'.format(style)
    return path.join(path.dirname(__file__), filename)


typeface = Typeface(
    'DejaVu Serif', OpenTypeFont(otf(''), weight=REGULAR),
    OpenTypeFont(otf('-Italic'), weight=REGULAR, slant=ITALIC),
    OpenTypeFont(otf('-Bold'), weight=BOLD),
    OpenTypeFont(otf('-BoldItalic'), weight=BOLD, slant=ITALIC),
    OpenTypeFont(otf('Condensed'), weight=REGULAR, width=CONDENSED),
    OpenTypeFont(otf('Condensed-Italic'),
                 weight=REGULAR,
                 slant=ITALIC,
                 width=CONDENSED),
    OpenTypeFont(otf('Condensed-Bold'), weight=BOLD, width=CONDENSED),
    OpenTypeFont(otf('Condensed-BoldItalic'),
                 weight=BOLD,
                 slant=ITALIC,
                 width=CONDENSED))
Example #6
0
def main():
    global parser
    args = parser.parse_args()
    do_exit = False
    if args.docs:
        webbrowser.open(DOCS_URL)
        return
    if args.list_templates:
        print('Installed document templates:')
        for name, _ in sorted(DocumentTemplate.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_stylesheets:
        print('Installed style sheets:')
        for name, _ in sorted(StyleSheet.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_formats:
        print('Supported input file formats:')
        for entry_point in iter_entry_points('rinoh.frontends'):
            reader_cls = entry_point.load()
            distribution = get_distribution_str(entry_point)
            print('- {} (.{}) [{}]'
                  .format(entry_point.name, ', .'.join(reader_cls.extensions),
                          distribution))
        do_exit = True
    if args.list_options:
        reader_name, reader_cls = get_reader_by_name(args.list_options)
        if list(reader_cls.supported_attributes):
            print('Options supported by the {} frontend'.format(reader_name))
            for name in reader_cls.supported_attributes:
                attr_def = reader_cls.attribute_definition(name)
                print('- {} ({}): {}. Default: {}'
                      .format(name, attr_def.accepted_type.__name__,
                              attr_def.description, attr_def.default_value))
        else:
            print('The {} frontend takes no options'.format(reader_name))
        do_exit = True
    if args.list_fonts:
        if args.list_fonts is object:
            print('Installed fonts:')
            for typeface, distribution in installed_typefaces():
                print('- {} [{}]' .format(typeface.name, distribution))
                widths = OrderedDict()
                for font in typeface.fonts():
                    widths.setdefault(font.width, []).append(font)
                for width, fonts in widths.items():
                    styles = []
                    for font in fonts:
                        style = font.weight.title()
                        if font.slant != FontSlant.UPRIGHT:
                            style = '{}-{}'.format(font.slant.title(), style)
                        styles.append(style)
                    print('   {}: {}'.format(width.title(), ', '.join(styles)))
        else:
            display_fonts(args.list_fonts)
        do_exit = True
    if do_exit:
        return

    if args.input is None:
        parser.print_help()
        return

    template_cfg = {}
    variables = {}
    if args.stylesheet:
        if os.path.isfile(args.stylesheet):
            stylesheet = StyleSheetFile(args.stylesheet, matcher=matcher)
        else:
            try:
                stylesheet = StyleSheet.from_string(args.stylesheet)
            except ResourceNotInstalled as err:
                raise SystemExit("Could not find the Style sheet '{}'. "
                                 "Aborting.\n"
                                 "Run `{} --list-stylesheets` to find out "
                                 "which style sheets are available."
                                 .format(err.resource_name, parser.prog))
        template_cfg['stylesheet'] = stylesheet

    if args.paper:
        try:
            variables['paper_size'] = Paper.from_string(args.paper.lower())
        except ValueError:
            accepted = ', '.join(sorted(paper.name for paper
                                        in PAPER_BY_NAME.values()))
            raise SystemExit("Unknown paper size '{}'. Must be one of:\n"
                             "   {}".format(args.paper, accepted))

    if not os.path.exists(args.input):
        raise SystemExit('{}: No such file'.format(args.input))
    input_dir, input_filename = os.path.split(args.input)
    input_root, input_ext = os.path.splitext(input_filename)
    reader_name, reader_cls = (get_reader_by_name(args.format) if args.format
                               else get_reader_by_extension(input_ext[1:]))
    str_options = dict((part.strip() for part in option.split('=', maxsplit=1))
                       for option, in args.option)
    try:
        options = {}
        for key, str_value in str_options.items():
            attr_def = reader_cls.attribute_definition(key)
            options[key] = attr_def.accepted_type.from_string(str_value)
    except KeyError as e:
        raise SystemExit('The {} frontend does not accept the option {}'
                         .format(reader_name, e))
    except ValueError as e:
        raise SystemExit("The value passed to the '{}' option is not valid:\n"
                         '  {}'.format(key, e))
    reader = reader_cls(**options)

    if os.path.isfile(args.template):
        template_cfg['base'] = TemplateConfigurationFile(args.template)
        template_cls = template_cfg['base'].template
    else:
        template_cls = DocumentTemplate.from_string(args.template)
    configuration = template_cls.Configuration('rinoh command line options',
                                               **template_cfg)
    configuration.variables.update(variables)

    document_tree = reader.parse(args.input)
    document = template_cls(document_tree, configuration=configuration)
    while True:
        try:
            success = document.render(input_root)
            if not success:
                raise SystemExit('Rendering completed with errors')
            break
        except ResourceNotInstalled as err:
            not_installed_msg = ("{} '{}' not installed."
                                 .format(err.resource_type.title(),
                                         err.resource_name))
            if args.install_resources:
                print(not_installed_msg + ' Attempting to install it from '
                                          'PyPI...')
                success = Typeface.install_from_pypi(err.entry_point_name)
                if not success:
                    raise SystemExit("No '{}' {} found on PyPI. Aborting."
                                     .format(err.resource_name,
                                             err.resource_type))
            else:
                raise SystemExit(not_installed_msg + " Consider passing the "
                                 "--install-resources command line option.")
Example #7
0
def test_missingglyph_type1():
    times = Typeface('Times')
    font = times.get_font(weight=FontWeight.REGULAR)
    with pytest.raises(MissingGlyphException):
        font.get_glyph('\u2024', 'normal')
from os import path

from rinoh.font import Typeface
from rinoh.font.opentype import OpenTypeFont

__all__ = ['typeface']


def otf(style):
    filename = 'DejaVuSansMono{}.ttf'.format(style)
    return OpenTypeFont(path.join(path.dirname(__file__), filename))


typeface = Typeface('DejaVu Sans Mono', otf(''), otf('-Oblique'), otf('-Bold'),
                    otf('-BoldOblique'))
Example #9
0
from os import path

from rinoh.font import Typeface
from rinoh.font.style import REGULAR, BOLD
from rinoh.font.opentype import OpenTypeFont

__all__ = ['typeface']


def otf(style):
    filename = 'notosanscjkjp-{}.otf'.format(style)
    return path.join(path.dirname(__file__), filename)


typeface = Typeface('Noto Sans CJK JP',
                    OpenTypeFont(otf('regular'), weight=REGULAR),
                    OpenTypeFont(otf('bold'), weight=BOLD))
Example #10
0
def test_missingglyph_type1():
    times = Typeface('Times')
    font = times.get_font(weight='regular')
    with pytest.raises(MissingGlyphException):
        font.get_glyph('\u2024', 'normal')
Example #11
0
def main():
    global parser
    args = parser.parse_args()
    do_exit = False
    if args.list_templates:
        print('Installed document templates:')
        for name in sorted(DocumentTemplate.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if args.list_stylesheets:
        print('Installed style sheets:')
        for name in sorted(StyleSheet.installed_resources):
            print('- {}'.format(name))
        do_exit = True
    if do_exit:
        return

    try:
        input_dir, input_filename = os.path.split(args.input)
    except AttributeError:
        parser.print_help()
        return

    kwargs = {}
    if args.stylesheet:
        if os.path.exists(args.stylesheet):
            stylesheet = StyleSheetFile(args.stylesheet, matcher=matcher)
        else:
            try:
                stylesheet = StyleSheet.from_string(args.stylesheet)
            except ResourceNotInstalled as err:
                raise SystemExit("Could not find the Style sheet '{}'. "
                                 "Aborting.\n"
                                 "Run `{} --list-stylesheets` to find out "
                                 "which style sheets are available.".format(
                                     err.resource_name, parser.prog))
        kwargs['stylesheet'] = stylesheet

    try:
        kwargs['paper_size'] = getattr(paper, args.paper.upper())
    except AttributeError:
        print("Unknown paper size '{}'. Must be one of:".format(args.paper))
        print('   A0, A1, ..., A10, letter, legal, junior_legal, ledger, '
              'tabloid')
        return

    input_root, input_ext = os.path.splitext(input_filename)
    if input_dir:
        os.chdir(input_dir)

    parser = ReStructuredTextReader()
    with open(input_filename) as input_file:
        document_tree = parser.parse(input_file)

    template = DocumentTemplate.from_string(args.template)
    configuration = template.Configuration(**kwargs)
    document = template(document_tree,
                        configuration=configuration,
                        backend=pdf)

    while True:
        try:
            document.render(input_root)
            break
        except ResourceNotInstalled as err:
            print("Typeface '{}' not installed. Attempting to install it from "
                  "PyPI...".format(err.resource_name))
            # answer = input()
            success = Typeface.install_from_pypi(err.entry_point_name)
            if not success:
                raise SystemExit(
                    "No '{}' typeface found on PyPI. Aborting.".format(
                        err.resource_name))
Example #12
0
def test_dynamic_entry_points():
    register_template('my_template', MyTemplate)
    register_typeface('swiss', helvetica)

    assert DocumentTemplate.from_string('my_template') is MyTemplate
    assert Typeface.from_string('swiss') is helvetica