示例#1
0
def main():
    parser = argparse.ArgumentParser(description='Render a reStructuredText '
                                                 'document to PDF.')
    parser.add_argument('input', type=str, nargs='?',
                       help='the reStructuredText document to render')
    parser.add_argument('--paper', type=str, nargs='?', default='A4',
                       help='the paper size to render to (default: A4)')
    args = parser.parse_args()

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

    try:
        page_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)
    options = ArticleOptions(page_size=page_size)
    document = Article(document_tree, options, backend=pdf)
    document.render(input_root)
示例#2
0
def render_rst_file(rst_path, out_filename, reference_path):
    reader = ReStructuredTextReader()
    doctree = reader.parse(rst_path)
    stylesheet_path = rst_path.with_suffix('.rts')
    config = (TemplateConfiguration(
        'rst', template=MinimalTemplate, stylesheet=str(stylesheet_path))
              if stylesheet_path.exists() else None)
    render_doctree(doctree, out_filename, reference_path, config)
示例#3
0
def render_rst_file(rst_path, out_filename, reference_path):
    reader = ReStructuredTextReader()
    doctree = reader.parse(rst_path)
    stylesheet_path = rst_path.with_suffix('.rts')
    config = (TemplateConfiguration('rst', template=MinimalTemplate,
                                    stylesheet=str(stylesheet_path))
              if stylesheet_path.exists() else None)
    render_doctree(doctree, out_filename, reference_path, config)
示例#4
0
def render_rst_file(rst_path, out_filename, reference_path):
    reader = ReStructuredTextReader()
    doctree = reader.parse(rst_path)
    kwargs = {}
    stylesheet_path = rst_path.with_suffix('.rts')
    if stylesheet_path.exists():
        kwargs['stylesheet'] = str(stylesheet_path)
    templconf_path = rst_path.with_suffix('.rtt')
    if templconf_path.exists():
        config = TemplateConfigurationFile(str(templconf_path))
    else:
        config = TemplateConfiguration('rst', template=MinimalTemplate, **kwargs)
        config.variables['paper_size'] = 'a5'
    render_doctree(doctree, out_filename, reference_path, config)
示例#5
0
def test_rstdemo(tmpdir):
    config = TemplateConfigurationFile(os.path.join(TEST_DIR, 'rstdemo.rtt'))

    parser = ReStructuredTextReader()
    flowables = parser.parse(os.path.join(TEST_DIR, 'demo.txt'))
    document = config.document(flowables)
    with in_directory(tmpdir.strpath):
        document.render('demo')
        _, _, _, badlinks, _, _ = check_pdf_links('demo.pdf')
        pytest.assume(badlinks == ['table-of-contents'])
        if not diff_pdf(os.path.join(TEST_DIR, 'reference/demo.pdf'),
                        'demo.pdf'):
            pytest.fail('The generated PDF is different from the reference '
                        'PDF.\nGenerated files can be found in {}'
                        .format(tmpdir.strpath))
示例#6
0
def render(source, filename):
    from rinoh.frontend.sphinx import nodes  # load the Sphinx docutils nodes

    file = BytesIO('\n'.join(source).encode('utf-8'))
    reader = ReStructuredTextReader()
    doctree = reader.parse(file)
    document = Minimal(doctree)
    tmpdir = tempfile.mkdtemp()
    document.render(path.join(tmpdir, filename))
    pdf_filename = '{}.pdf'.format(filename)
    with in_directory(tmpdir):
        _, _, _, badlinks, _, _ = check_pdf_links(pdf_filename)
        pytest.assume(badlinks == [])
        if not diff_pdf(path.join(TEST_DIR, 'reference', pdf_filename),
                        pdf_filename):
            pytest.fail(
                'The generated PDF is different from the reference '
                'PDF.\nGenerated files can be found in {}'.format(tmpdir))
示例#7
0
def test_rstdemo(tmpdir):
    configuration = Article.Configuration(stylesheet=sphinx_base14,
                                          abstract_location='title',
                                          table_of_contents=False)
    configuration('title_page', top_margin=2 * CM)

    with open(os.path.join(TEST_DIR, 'demo.txt')) as file:
        parser = ReStructuredTextReader()
        flowables = parser.parse(file)
    document = Article(flowables, configuration=configuration, backend=pdf)
    os.chdir(tmpdir.strpath)
    document.render('demo')
    _, _, _, badlinks, _, _ = check_pdf_links('demo.pdf')
    pytest.assume(badlinks == ['table-of-contents'])
    if not diff_pdf(os.path.join(TEST_DIR, 'reference/demo.pdf'), 'demo.pdf'):
        pytest.fail('The generated PDF is different from the reference PDF.\n'
                    'Generated files can be found in {}'.format(
                        tmpdir.strpath))
示例#8
0
 def write_doc(self, docname, doctree, docnames, targetname):
     config = self.config
     parser = ReStructuredTextReader()
     rinoh_tree = parser.from_doctree(doctree['source'], doctree)
     template_cfg = template_from_config(config, self.confdir,
                                         logger.warning)
     rinoh_document = template_cfg.document(rinoh_tree)
     extra_indices = StaticGroupedFlowables(self.generate_indices(docnames))
     rinoh_document.insert('back_matter', 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)
示例#9
0
def test_rstdemo():
    config = TemplateConfigurationFile(TEST_DIR / 'rstdemo.rtt')

    parser = ReStructuredTextReader()
    flowables = parser.parse(TEST_DIR / 'demo.txt')
    document = config.document(flowables)
    out_dir = OUTPUT_DIR / 'rstdemo'
    out_dir.mkdir(parents=True, exist_ok=True)
    pdf_filename = 'demo.pdf'
    _, _, _, _, _, _, ref_outlines = check_pdf_links(TEST_DIR / 'reference'
                                                     / pdf_filename)
    with in_directory(out_dir):
        document.render('demo')
        _, _, _, badlinks, _, _, outlines = check_pdf_links(pdf_filename)
        pytest.assume(badlinks == ['table-of-contents'])
        pytest.assume(ref_outlines == outlines)
        if not diff_pdf(TEST_DIR / 'reference' / 'demo.pdf', 'demo.pdf'):
            pytest.fail('The generated PDF is different from the reference '
                        'PDF.\nGenerated files can be found in {}'
                        .format(out_dir))
示例#10
0
def test_rstdemo():
    config = TemplateConfigurationFile(TEST_DIR / 'rstdemo.rtt')

    parser = ReStructuredTextReader()
    flowables = parser.parse(TEST_DIR / 'demo.txt')
    document = config.document(flowables)
    out_dir = OUTPUT_DIR / 'rstdemo'
    out_dir.mkdir(parents=True, exist_ok=True)
    pdf_filename = 'demo.pdf'
    _, _, _, _, _, _, ref_outlines = check_pdf_links(TEST_DIR / 'reference' /
                                                     pdf_filename)
    with in_directory(out_dir):
        document.render('demo')
        _, _, _, badlinks, _, _, outlines = check_pdf_links(pdf_filename)
        pytest.assume(badlinks == ['table-of-contents'])
        pytest.assume(ref_outlines == outlines)
        if not diff_pdf(TEST_DIR / 'reference' / 'demo.pdf', 'demo.pdf'):
            pytest.fail(
                'The generated PDF is different from the reference '
                'PDF.\nGenerated files can be found in {}'.format(out_dir))
示例#11
0
文件: tool.py 项目: calve/rinohtype
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))
示例#12
0
def render_rst_file(rst_path, out_filename, reference_path, tmpdir):
    reader = ReStructuredTextReader()
    doctree = reader.parse(rst_path)
    render_doctree(doctree, out_filename, reference_path, tmpdir)
示例#13
0
def render_rst_file(rst_path, out_filename, reference_path):
    reader = ReStructuredTextReader()
    doctree = reader.parse(rst_path)
    return _render_rst(rst_path, doctree, out_filename, reference_path)
示例#14
0
文件: test.py 项目: frol/rinohtype
from rinoh.paper import A5
from rinoh.backend import pdf
from rinoh.frontend.rst import ReStructuredTextReader

from rinohlib.stylesheets.somestyle import stylesheet as STYLESHEET
from rinohlib.templates.book import Book, BookOptions
from rinohlib.templates.article import Article, ArticleOptions

if __name__ == '__main__':
    for name in ('quickstart', 'demo', 'FAQ', 'THANKS'):
        parser = ReStructuredTextReader()
        with open(name + '.txt') as file:
            flowables = parser.parse(file)
        # manual_options = BookOptions(stylesheet=STYLESHEET)
        # document = Book(document_tree, options=manual_options, backend=pdf)
        article_options = ArticleOptions(table_of_contents=False, page_size=A5)
        document = Article(flowables, options=article_options, backend=pdf)
        document.render(name)
示例#15
0
文件: test.py 项目: z00sts/rinohtype
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)
示例#16
0
文件: test.py 项目: calve/rinohtype
from rinoh.backend import pdf
from rinoh.dimension import CM
from rinoh.frontend.rst import ReStructuredTextReader
from rinoh.structure import AdmonitionTitles
from rinoh.stylesheets import sphinx_article
from rinoh.templates import Article


if __name__ == '__main__':
    strings = (AdmonitionTitles(important='IMPORTANT:',
                                tip='TIP:'),
               )

    configuration = Article.Configuration(stylesheet=sphinx_article,
                                          abstract_location='title',
                                          table_of_contents=False)
    configuration('title_page', top_margin=2 * CM)

    for name in ('demo', 'quickstart', 'FAQ', 'THANKS'):
        parser = ReStructuredTextReader()
        with open(name + '.txt') as file:
            flowables = parser.parse(file)
        document = Article(flowables, strings=strings,
                           configuration=configuration, backend=pdf)
        document.render(name)
示例#17
0
文件: test.py 项目: brechtm/rinohtype
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)