Пример #1
0
def get_ast_as_pdf(s, parse_expr):
    s = s.replace('\t', '    ')
    contents = ast_to_html(s,
                       ignore_line=None, parse_expr=parse_expr,
                       add_line_gutter=False)
    html = get_minimal_document(contents)
    
    mcdp_tmp_dir = get_mcdp_tmp_dir()
    prefix = 'get_ast_as_pdf()'
    d = mkdtemp(dir=mcdp_tmp_dir, prefix=prefix)
    
    try:
        f_html = os.path.join(d, 'file.html')
        with open(f_html, 'w') as f:
            f.write(html)
            
        try:
            f_pdf = os.path.join(d, 'file.pdf')
            cmd= ['wkhtmltopdf','-s','A1',f_html,f_pdf]
            system_cmd_result(
                    d, cmd, 
                    display_stdout=False,
                    display_stderr=False,
                    raise_on_error=True)
    
            with open(f_pdf) as f:
                data = f.read()
            
            data = crop_pdf(data, margins=0)
    
            return data
        except CmdException as e:
            raise e
    finally:
        shutil.rmtree(d)
Пример #2
0
    def __init__(self,
                 gg,
                 parent,
                 yourname,
                 level=0,
                 tmppath=None,
                 style='default',
                 image_source=None,
                 skip_initial=True):
        self.gg = gg
        self.parent = parent
        self.yourname = yourname
        self.level = level
        #         self.library = library

        if tmppath is None:
            d = get_mcdp_tmp_dir()
            prefix = 'GraphDrawingContext_tmppath'
            tmppath = mkdtemp(dir=d, prefix=prefix)
            mcdp_dev_warning('need to share icons')

        self.tmppath = tmppath
        self.image_source = image_source

        self.all_nodes = []

        self.set_style(style)
        self.skip_initial = skip_initial
Пример #3
0
def crop_pdf(pdf, margins=0):
    
    mcdp_tmp_dir = get_mcdp_tmp_dir()
    prefix = 'crop_pdf()'
    d = mkdtemp(dir=mcdp_tmp_dir, prefix=prefix)
    
    try:
        f_pdf = os.path.join(d, 'file.pdf')
        with open(f_pdf, 'w') as f:
            f.write(pdf)
        f_pdf_crop = os.path.join(d, 'file_crop.pdf')
        cmd = [
            'pdfcrop', 
            '--margins', 
            str(margins), 
            f_pdf, 
            f_pdf_crop,
        ]
        system_cmd_result(
                d, cmd,
                display_stdout=False,
                display_stderr=False,
                raise_on_error=True)
    
        with open(f_pdf_crop) as f:
            data = f.read()
        return data
    finally:
        shutil.rmtree(d)
Пример #4
0
def get_link_to_image_file(filename, max_width):
    basename, ext = os.path.splitext(os.path.basename(filename).lower())
    if ext in ['.jpg', '.jpeg']:
        with open(filename) as f:
            im = Image.open(f)
            # print filename, im.size
            if im.size[0] > max_width:
                b = basename + '-' + get_md5(filename)[:4] + '.jpg'
                dest = os.path.join(get_mcdp_tmp_dir(), 'images', b)
                height = int(im.size[1] * max_width / im.size[0])
                new_size = (max_width, height)
                msg = 'Resizing image %s from %s to %s' % (filename, im.size,
                                                           new_size)
                logger.info(msg)
                # print('resizing to %s in %s' % (str(new_size), dest))
                if not os.path.exists(dest):
                    make_sure_dir_exists(dest)
                    resized = im.resize(new_size)

                    resized.save(dest)

                return dest
            # im.save(file + ".thumbnail", "JPEG")

        return filename
    else:
        return filename
Пример #5
0
def resize_icon(filename, size):
    check_isinstance(filename, str)
    
    tmppath = get_mcdp_tmp_dir()
    res = os.path.join(tmppath, 'resized', str(size))

    safe_makedirs(res)
    resized = os.path.join(res, os.path.basename(filename))
    if not os.path.exists(resized):
        cmd = ['convert', 
               filename, 
               '-resize', '%s' % size, 
               # remove alpha - otherwise lulu complains
               '-background', 'white',
                '-alpha','remove',
                '-alpha','off', 
               resized]
        try:

            system_cmd_result(cwd='.', cmd=cmd,
                     display_stdout=False,
                     display_stderr=False,
                     raise_on_error=True)

        except CmdException:
            raise
    return resized
Пример #6
0
 def use_tmp_cache(self):
     """ Uses a temporary directory as cache. """
     import tempfile
     d = get_mcdp_tmp_dir()
     prefix = 'MCDPLibrary_use_tmp_cache'
     dirname = tempfile.mkdtemp(dir=d, prefix=prefix)
     self.use_cache_dir(dirname)
Пример #7
0
def get_test_library(libname):
    assert isinstance(libname,
                      str) and not MCDPConstants.library_extension in libname
    librarian = get_test_librarian()
    library = librarian.load_library(libname)

    d = get_mcdp_tmp_dir()
    prefix = 'mcdp_library_tests_get_test_library_'
    d = tempfile.mkdtemp(dir=d, prefix=prefix)

    library.use_cache_dir(d)
    # XXX: this does not erase the directory
    return library
Пример #8
0
def lessc_string(s1):
    """
        Runs "node lessc" on the string

        Raises LesscError.
    """
    #     print(indent(s1, 'lessc input: '))
    mcdp_tmp_dir = get_mcdp_tmp_dir()
    prefix = 'prerender_lessc'
    d = mkdtemp(dir=mcdp_tmp_dir, prefix=prefix)
    try:
        f1 = os.path.join(d, 'input.less')
        f2 = os.path.join(d, 'out.css')
        with open(f1, 'w') as f:
            f.write(s1)

        try:
            cmd = ['lessc', f1, f2]
            res = system_cmd_result(d,
                                    cmd,
                                    display_stdout=True,
                                    display_stderr=True,
                                    raise_on_error=False)

            if res.ret:
                msg = 'lessc error (return value = %d).' % res.ret
                msg += '\n\n' + indent(res.stderr, '', 'stderr:')
                msg += '\n\n' + indent(res.stdout, '', 'stdout:')
                raise LesscError(msg)

            with open(f2) as f:
                data = f.read()

            return data
        except CmdException as e:
            raise e
    finally:
        shutil.rmtree(d)
Пример #9
0
def prerender_mathjax_(html):
    """
        Runs the prerender.js script to pre-render the MathJax into images.

        Raises PrerenderError.
    """
    assert not '<html>' in html, html

    use = get_nodejs_bin()

    html = html.replace('<p>$$', '\n$$')
    html = html.replace('$$</p>', '$$\n')
    script = get_prerender_js()
    mcdp_tmp_dir = get_mcdp_tmp_dir()
    prefix = 'prerender_mathjax_'
    d = mkdtemp(dir=mcdp_tmp_dir, prefix=prefix)

    try:
        f_html = os.path.join(d, 'file.html')
        with open(f_html, 'w') as f:
            f.write(html)

        try:
            f_out = os.path.join(d, 'out.html')
            cmd = [use, script, f_html, f_out]
            pwd = os.getcwd()
            res = system_cmd_result(pwd,
                                    cmd,
                                    display_stdout=False,
                                    display_stderr=False,
                                    raise_on_error=False)

            if res.ret:  # pragma: no cover
                if 'Error: Cannot find module' in res.stderr:
                    msg = 'You have to install the MathJax and/or jsdom libraries.'
                    msg += '\nOn Ubuntu, you can install them using:'
                    msg += '\n\n\tsudo apt-get install npm'
                    msg += '\n\n\tnpm install MathJax-node jsdom'
                    msg += '\n\n' + indent(res.stderr, '  |')
                    raise PrerenderError(msg)

                if 'parse error' in res.stderr:
                    lines = [
                        _ for _ in res.stderr.split('\n') if 'parse error' in _
                    ]
                    assert lines
                    msg = 'LaTeX conversion errors:\n\n' + '\n'.join(lines)
                    raise PrerenderError(msg)

                msg = 'Unknown error (ret = %d).' % res.ret
                msg += '\n\n' + indent(res.stderr, '  |')
                raise PrerenderError(msg)

            with open(f_out) as f:
                data = f.read()

            # Read the data
            soup = bs(data)
            # find this and move it at the end
            # <style id="MathJax_SVG_styles"
            tag_style = soup.find(id='MathJax_SVG_styles')
            if not tag_style:
                msg = 'Expected to find style MathJax_SVG_styles'
                raise_desc(Exception, msg, soup=str(soup))
            # <svg style="display: none;"><defs id="MathJax_SVG_glyphs">
            tag_svg_defs = soup.find('svg', style="display: none;")
            if not tag_svg_defs:
                msg = 'Expected to find tag <svg display=none>'
                raise_desc(Exception, msg, soup=str(soup))

            other_tag = soup.find('div', style="display:none")
            if not other_tag:
                msg = 'Expected to find tag <div style="display:none">'
                raise_desc(Exception, msg, soup=str(soup))

            #<div style="display:none">Because of mathjax bug</div>
            soup.append(other_tag.extract())
            soup.append(tag_svg_defs.extract())
            soup.append(tag_style.extract())
            data = to_html_stripping_fragment(soup)

            return data
        except CmdException as e:  # pragma: no cover
            raise e
    finally:
        shutil.rmtree(d)