Example #1
0
    def highlighted_operations(self):
        from pygments.lexers import get_lexer_by_name
        from pygments.util import ClassNotFound
        from pygments import highlight
        from pygments.formatters import get_formatter_by_name
        from wordinserter import parse
        import warnings

        try:
            formatter = get_formatter_by_name("html")
            lexer = get_lexer_by_name(self.highlight)
        except ClassNotFound:
            warnings.warn("Lexer {0} or formatter html not found, not highlighting".format(self.highlight))
            return None

        formatter.noclasses = True

        highlighted_code = highlight(self.text, lexer=lexer, formatter=formatter)
        return parse(highlighted_code, parser="html")
Example #2
0
            print(file)
            temp_directory = pathlib.Path(tempfile.mkdtemp())

            document = word.Documents.Add()

            try:
                content = file.open().read()

                if not content.strip():
                    continue

                print("Rendering {0}".format(file.name))

                parse_start = time.time()
                operations = parse(content,
                                   parser="html" if file.name.endswith("html")
                                   else "markdown")
                parse_end = time.time()

                render_start = time.time()
                insert(operations, document=document, constants=constants)
                render_end = time.time()

                # Now we export the document as a PDF:
                pdf_path = temp_directory / (file.name + ".pdf")
                document.SaveAs2(str(pdf_path), 17)

                # Now convert that PDF to a PNG
                png_path = temp_directory / (file.name + ".png")
                convert_command = '"{0}" -interlace none -density 300 -quality 80 {1} -trim {2} '.format(
                    imagemagick, str(pdf_path), str(png_path))
    for file in file_names:
        if file.name.endswith(".html") or file.name.endswith(".md"):

            document = word.Documents.Add()

            try:
                content = file.open().read()

                if not content.strip():
                    continue

                print("Rendering {0}".format(file.name))

                parse_start = time.time()
                operations = parse(content, parser="html" if file.name.endswith("html") else "markdown")
                parse_end = time.time()

                render_start = time.time()
                insert(operations, document=document, constants=constants)
                render_end = time.time()

                # Now we export the document as a PDF:
                pdf_path = temp_directory / (file.name + ".pdf")
                document.SaveAs2(str(pdf_path), 17)

                # Now convert that PDF to a PNG
                png_path = temp_directory / (file.name + ".png")

                code = subprocess.call(
                    '"{0}" -interlace none -density 300 -trim -quality 80 {1} {2} '.format(
def run():
    arguments = docopt(__doc__, version='0.1')

    if arguments['<path>'] == '-':
        text = sys.stdin.read()
    else:
        text = get_file_contents(arguments['<path>'])

    css = []

    if arguments['--css']:
        css.append(get_file_contents(arguments['--css']))

    if arguments['--style']:
        css.append(arguments['--style'])

    save_as = None
    if arguments['--save']:
        save_as = pathlib.Path(arguments['--save'])
        if save_as.suffix not in SAVE_FORMATS:
            print('Error: Cannot save in {0} format. Supported formats: {1}'.format(
                save_as.suffix,
                ', '.join(SAVE_FORMATS.keys())
            ), file=sys.stderr)
            exit(1)

        if save_as.exists():
            print('Error: Path {0} already exists. Not overwriting'.format(save_as), file=sys.stderr)
            exit(1)

    with Timer(factor=1000) as t:
        parsed = parse(text, stylesheets=css)

    print('Parsed in {0:f} ms'.format(t.elapsed))

    with Timer(factor=1000) as t:
        try:
            word = CreateObject("Word.Application")
        except AttributeError as e:
            gen_dir = inspect.getsourcefile(gen)

            print('****** There was an error opening word ******')
            print('This is a transient error that sometimes happens.')
            print('Remove all files (except __init__.py) from here:')
            print(os.path.dirname(gen_dir))
            print('Then retry the program')
            print('*********************************************')
            raise e
        doc = word.Documents.Add()

    print('Opened word in {0:f} ms'.format(t.elapsed))

    word.Visible = not arguments['--hidden']

    from comtypes.gen import Word as constants

    with Timer(factor=1000) as t:
        insert(parsed, document=doc, constants=constants, debug=arguments['--debug'])

    print('Inserted in {0:f} ms'.format(t.elapsed))

    if save_as:
        file_format_attr = SAVE_FORMATS[save_as.suffix]

        if callable(file_format_attr):
            file_format_attr(doc, save_as, constants)
        else:
            # https://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas2.aspx
            doc.SaveAs2(
                FileName=str(save_as.absolute()),
                FileFormat=getattr(constants, file_format_attr),
            )
        print('Saved to {0}'.format(save_as))

    if arguments['--close']:
        word.Quit(SaveChanges=constants.wdDoNotSaveChanges)