def template_from_config(config, confdir, warn): template_cfg = {} if isinstance(config.rinoh_template, str): tmpl_path = path.join(confdir, config.rinoh_template) if path.isfile(tmpl_path): template_cfg['base'] = TemplateConfigurationFile(tmpl_path) template_cls = template_cfg['base'].template else: template_cls = DocumentTemplate.from_string(config.rinoh_template) elif isinstance(config.rinoh_template, TemplateConfiguration): template_cfg['base'] = config.rinoh_template template_cls = config.rinoh_template.template else: template_cls = config.rinoh_template if isinstance(config.rinoh_stylesheet, str): stylesheet_path = path.join(confdir, config.rinoh_stylesheet) stylesheet = StyleSheet.from_string(stylesheet_path if path.isfile( stylesheet_path) else config.rinoh_stylesheet) else: stylesheet = config.rinoh_stylesheet if config.pygments_style is not None: if stylesheet is not None: base = stylesheet elif 'base' in template_cfg: base = template_cfg['base']['stylesheet'] else: base = template_cls.stylesheet.default_value stylesheet = pygments_style_to_stylesheet(config.pygments_style, base) if stylesheet is not None: template_cfg['stylesheet'] = stylesheet language = config.language if language: try: template_cfg['language'] = Language.from_string(language) except KeyError: warn('The language "{}" is not supported by rinohtype.'.format( language)) variables = {} if config.rinoh_paper_size: variables['paper_size'] = config.rinoh_paper_size sphinx_config = template_cls.Configuration('Sphinx conf.py options', **template_cfg) sphinx_config.variables.update(variables) return sphinx_config
def template_from_config(config, confdir, warn): template_cfg = {} if isinstance(config.rinoh_template, str): tmpl_path = path.join(confdir, config.rinoh_template) if path.isfile(tmpl_path): template_cfg['base'] = TemplateConfigurationFile(tmpl_path) template_cls = template_cfg['base'].template else: template_cls = DocumentTemplate.from_string(config.rinoh_template) elif isinstance(config.rinoh_template, TemplateConfiguration): template_cfg['base'] = config.rinoh_template template_cls = config.rinoh_template.template else: template_cls = config.rinoh_template if isinstance(config.rinoh_stylesheet, str): stylesheet_path = path.join(confdir, config.rinoh_stylesheet) stylesheet = StyleSheet.from_string(stylesheet_path if path.isfile(stylesheet_path) else config.rinoh_stylesheet) else: stylesheet = config.rinoh_stylesheet if config.pygments_style is not None: if stylesheet is not None: base = stylesheet elif 'base' in template_cfg: base = template_cfg['base']['stylesheet'] else: base = template_cls.stylesheet.default_value stylesheet = pygments_style_to_stylesheet(config.pygments_style, base) if stylesheet is not None: template_cfg['stylesheet'] = stylesheet language = config.language if language: try: template_cfg['language'] = Language.from_string(language) except KeyError: warn('The language "{}" is not supported by rinohtype.') variables = {} if config.rinoh_paper_size: variables['paper_size'] = config.rinoh_paper_size sphinx_config = template_cls.Configuration('Sphinx conf.py options', **template_cfg) sphinx_config.variables.update(variables) return sphinx_config
def write_doc(self, docname, doctree, docnames, targetname): config = self.config suffix, = config.source_suffix source_path = os.path.join(self.srcdir, docname + suffix) parser = ReStructuredTextReader() rinoh_tree = parser.from_doctree(source_path, doctree) rinoh_document_template = config.rinoh_document_template template = (DocumentTemplate.from_string(rinoh_document_template) if isinstance(rinoh_document_template, str) else rinoh_document_template) if isinstance(self.config.rinoh_stylesheet, str): stylesheet = StyleSheet.from_string(self.config.rinoh_stylesheet) elif self.config.rinoh_stylesheet is None: stylesheet = template.Configuration.stylesheet.default_value else: stylesheet = self.config.rinoh_stylesheet if config.pygments_style is not None: stylesheet = pygments_style_to_stylesheet(config.pygments_style, stylesheet) paper_size = config.rinoh_paper_size base_config = template.Configuration(paper_size=paper_size, stylesheet=stylesheet) if config.rinoh_template_configuration is not None: template_configuration = config.rinoh_template_configuration if template_configuration.base is None: template_configuration.base = base_config else: template_configuration = base_config rinoh_document = template(rinoh_tree, configuration=template_configuration, backend=pdf) extra_indices = StaticGroupedFlowables(self.generate_indices(docnames)) rinoh_document.insert('indices', extra_indices, 0) rinoh_logo = config.rinoh_logo if rinoh_logo: rinoh_document.metadata['logo'] = rinoh_logo rinoh_document.metadata['title'] = doctree.settings.title rinoh_document.metadata['subtitle'] = ('Release {}'.format( config.release)) rinoh_document.metadata['author'] = doctree.settings.author outfilename = path.join(self.outdir, os_path(targetname)) ensuredir(path.dirname(outfilename)) rinoh_document.render(outfilename)
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, dist in find_entry_points('rinoh.frontends'): reader_cls = entry_point.load() print('- {} (.{}) [{}]'.format(entry_point.name, ', .'.join(reader_cls.extensions), get_distribution_name(dist))) 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 = FontWeight.to_name(font.weight) if font.slant != FontSlant.UPRIGHT: style = '{}-{}'.format(font.slant, style) styles.append(style) print(' {}: {}'.format(FontWidth.to_name(width), ', '.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 = {} cwd_source = CwdSource() if args.stylesheet: if os.path.isfile(args.stylesheet): stylesheet = StyleSheetFile(args.stylesheet, matcher=matcher, source=cwd_source) else: try: stylesheet = StyleSheet.from_string(args.stylesheet) except ResourceNotFound 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) if args.output: if os.path.isdir(args.output): output_path = os.path.join(args.output, input_root) else: output_path = args.output else: output_path = input_root 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, source=cwd_source) 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(output_path) if not success: raise SystemExit('Rendering completed with errors') break except ResourceNotFound as err: if args.install_resources: print( "Attempting to the install the '{}' {} from PyPI:".format( err.resource_name, err.resource_type.title())) 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. Consider passing the " "--install-resources command line option.".format( err.resource_type.title(), err.resource_name))
from rinoh.dimension import PT, CM from rinoh.font.style import REGULAR, SUPERSCRIPT from rinoh.number import NUMBER from rinoh.paragraph import LEFT, CENTER from rinoh.text import FixedWidthSpace from rinoh.style import StyleSheet, Var from rinohlib.stylesheets.ieee import styles as IEEE_STYLESHEET stylesheet = StyleSheet('SomeStyle', base=IEEE_STYLESHEET) stylesheet('body', base=stylesheet.base['body'], indent_first=0, space_below=6*PT) stylesheet('heading level 1', typeface=Var('ieee_family').sans, font_size=14*PT, space_above=18*PT, space_below=6*PT, label_suffix=FixedWidthSpace()) stylesheet('heading level 2', base='heading level 1', font_size=12*PT, space_above=6*PT, space_below=6*PT, label_suffix=FixedWidthSpace())
paragraph3_selector = Paragraph.like('paragraph3') paragraph4_selector = Paragraph.like('paragraph4') missing_selector = Paragraph.like('missing') matcher = StyledMatcher({ 'emphasized text': emphasis_selector, 'emphasized text 2': emphasis2_selector, 'highlighted text': highlight_selector, 'highlighted text 2': highlight2_selector, 'paragraph': paragraph_selector, 'paragraph 2': paragraph2_selector, 'paragraph 4': paragraph4_selector, 'missing style': missing_selector, }) ssheet1 = StyleSheet('ssheet1', matcher) ssheet1.variables['font-size'] = 5 * PT ssheet1.variables['text-align'] = 'center' ssheet1.variables['font-color'] = HexColor('f00') ssheet1('emphasized text', font_slant='italic', font_size=Var('font-size')) ssheet1('emphasized text 2', base='emphasized text', font_slant='oblique') ssheet1('highlighted text', font_color=HexColor('00f')) ssheet1('highlighted text 2', base='highlighted text', font_size=12 * PT) ssheet1('paragraph', margin_right=55 * PT, space_above=5 * PT, text_align=Var('text-align'), font_size=8 * PT, font_color=Var('font-color'),
from rinoh.float import InlineImage from rinoh.font import TypeFace, TypeFamily from rinoh.font.style import REGULAR, ITALIC, LIGHT, BOLD from rinoh.font.opentype import OpenTypeFont from rinoh.paper import A4 from rinoh.paragraph import LEFT, TabStop, RIGHT, ProportionalSpacing from rinoh.reference import Variable, PAGE_NUMBER, SECTION_TITLE from rinoh.style import StyleSheet, Var from rinoh.table import MIDDLE from rinoh.text import Tab from rinohlib.stylesheets.sphinx import stylesheet as SPHINX from rinohlib.templates.article import ArticleOptions, TITLE stylesheet = StyleSheet("RinohDemo", base=SPHINX) # def os_filename(variant): # return path.join(path.dirname(__file__), # path.pardir, path.pardir, path.pardir, 'rinohdemo', # 'fonts', 'OpenSans-{}.ttf'.format(variant)) # # os_regular = OpenTypeFont(os_filename('Regular'), weight=REGULAR) # os_italic = OpenTypeFont(os_filename('Italic'), weight=REGULAR, slant=ITALIC) # os_light = OpenTypeFont(os_filename('Light'), weight=LIGHT) # os_bold = OpenTypeFont(os_filename('Bold'), weight=BOLD) # # open_sans = TypeFace('TeXGyrePagella', os_regular, os_italic, os_light, os_bold) # # stylesheet.variables['fonts'] = TypeFamily(serif=open_sans, # sans=SPHINX.variables['fonts'].sans,
FixedSpacing, ProportionalSpacing, SINGLE) from rinoh.dimension import PT, CM from rinoh.table import MIDDLE from rinoh.text import FixedWidthSpace from rinoh.number import NUMBER, SYMBOL from rinoh.color import Color, Gray, RED, GRAY90, GRAY50 from rinoh.font import TypeFamily from rinoh.font.style import REGULAR, ITALIC, BOLD, SUPERSCRIPT from rinohlib.fonts.texgyre.pagella import typeface as palatino from rinohlib.fonts.texgyre.cursor import typeface as courier from rinohlib.fonts.texgyre.heros import typeface as helvetica from .matcher import matcher stylesheet = StyleSheet('Sphinx', matcher=matcher) stylesheet.variables['fonts'] = TypeFamily(serif=palatino, sans=helvetica, mono=courier) stylesheet['default'] = ParagraphStyle(typeface=Var('fonts').serif, font_weight=REGULAR, font_size=10*PT, line_spacing=FixedSpacing(12*PT), indent_first=0*PT, space_above=0*PT, space_below=0*PT, justify=BOTH, kerning=True, ligatures=True,
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.")
from rinoh.dimension import PT from rinoh.document import DocumentTree, Document, FakeContainer from rinoh.language import EN from rinoh.paragraph import Paragraph from rinoh.text import StyledText, SingleStyledText from rinoh.style import StyleSheet, StyledMatcher, Specificity emphasis_selector = StyledText.like('emphasis') paragraph_selector = Paragraph matcher = StyledMatcher({ 'emphasized text': emphasis_selector, 'paragraph': paragraph_selector, }) ssheet1 = StyleSheet('base', matcher) ssheet1('emphasized text', font_slant='italic') ssheet1('paragraph', space_above=5 * PT) ssheet2 = StyleSheet('test', base=ssheet1) ssheet2('paragraph', space_below=10 * PT) emphasized = SingleStyledText('emphasized', style='emphasis') paragraph = Paragraph('A paragraph with ' + emphasized + ' text.') doctree = DocumentTree([paragraph]) document = Document(doctree, ssheet2, EN) container = FakeContainer(document)
BOTH, FixedSpacing, ProportionalSpacing, SINGLE) from rinoh.dimension import PT, CM from rinoh.table import MIDDLE from rinoh.text import FixedWidthSpace from rinoh.number import NUMBER, SYMBOL from rinoh.color import Color, Gray, RED, GRAY90, GRAY50 from rinoh.font import TypeFamily from rinoh.font.style import REGULAR, ITALIC, BOLD, SUPERSCRIPT from rinohlib.fonts.texgyre.pagella import typeface as palatino from rinohlib.fonts.texgyre.cursor import typeface as courier from rinohlib.fonts.texgyre.heros import typeface as helvetica from .matcher import matcher stylesheet = StyleSheet('Sphinx', matcher=matcher) stylesheet.variables['fonts'] = TypeFamily(serif=palatino, sans=helvetica, mono=courier) stylesheet['default'] = ParagraphStyle(typeface=Var('fonts').serif, font_weight=REGULAR, font_size=10 * PT, line_spacing=FixedSpacing(12 * PT), indent_first=0 * PT, space_above=0 * PT, space_below=0 * PT, justify=BOTH, kerning=True, ligatures=True,
from rinoh.frontend.rst import ReStructuredTextReader from rinoh.strings import Strings from rinoh.structure import AdmonitionTitles from rinoh.style import StyleSheet from rinoh.template import TemplateConfigurationFile if __name__ == '__main__': default_stylesheet = StyleSheet('empty') default_stylesheet.write('emtpy') strings = Strings(AdmonitionTitles(important='IMPORTANT:', tip='TIP:')) configuration = TemplateConfigurationFile('article.rtt') sphinx_stylesheet = configuration['stylesheet'].base sphinx_stylesheet.write('sphinx') for name in ('demo', 'quickstart', 'FAQ', 'THANKS'): parser = ReStructuredTextReader() document_tree = parser.parse(name + '.txt') document = configuration.document(document_tree) document.render(name)
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))
from rinoh.dimension import PERCENT, PT, CM from rinoh.float import InlineImage from rinoh.font import TypeFace, TypeFamily from rinoh.font.style import REGULAR, ITALIC, LIGHT, BOLD from rinoh.font.opentype import OpenTypeFont from rinoh.paper import A4 from rinoh.paragraph import LEFT, TabStop, RIGHT, ProportionalSpacing from rinoh.reference import Variable, PAGE_NUMBER, SECTION_TITLE from rinoh.style import StyleSheet, Var from rinoh.table import MIDDLE from rinoh.text import Tab from rinohlib.stylesheets.sphinx import stylesheet as SPHINX from rinohlib.templates.article import ArticleOptions, TITLE stylesheet = StyleSheet('RinohDemo', base=SPHINX) # def os_filename(variant): # return path.join(path.dirname(__file__), # path.pardir, path.pardir, path.pardir, 'rinohdemo', # 'fonts', 'OpenSans-{}.ttf'.format(variant)) # # os_regular = OpenTypeFont(os_filename('Regular'), weight=REGULAR) # os_italic = OpenTypeFont(os_filename('Italic'), weight=REGULAR, slant=ITALIC) # os_light = OpenTypeFont(os_filename('Light'), weight=LIGHT) # os_bold = OpenTypeFont(os_filename('Bold'), weight=BOLD) # # open_sans = TypeFace('TeXGyrePagella', os_regular, os_italic, os_light, os_bold) # # stylesheet.variables['fonts'] = TypeFamily(serif=open_sans, # sans=SPHINX.variables['fonts'].sans,