Esempio n. 1
0
    def show(self, fmt="html", header_block=None, footer_block=None):
        """
        Show the block in a browser.

        :param fmt: The format of the saved block. Supports the same output as `Block.save`
        :return: Path to the block file.
        """
        file_name = str_base(hash(self._id)) + "." + fmt
        file_path = self.publish(os.path.expanduser(
            os.path.join(user_config["tmp_html_dir"], file_name)),
                                 header_block=header_block,
                                 footer_block=footer_block)

        try:
            url_base = user_config["public_dir"]
        except KeyError:
            path = os.path.expanduser(file_path)
        else:
            path = urljoin(
                url_base,
                os.path.expanduser(user_config["tmp_html_dir"] + "/" +
                                   file_name))

        webbrowser.open_new_tab(path)

        return path
Esempio n. 2
0
    def save(self, filename=None, fmt=None, toc=False, pdf_zoom=1, pdf_page_size="A4", pdf_auto_shrink=True,
             pretty=True, orientation='Portrait', header_block=None, header_spacing=5, footer_block=None,
             footer_spacing=5, java_script_delay=200, **kwargs):
        """
        Render and save the block. Depending on whether the filename or the format is
        provided, the content will either be written out to a file or returned as a string.

        :param filename: Format will be based on the file extension.
                         The following formats are supported:
                         - HTML
                         - PDF
                         - PNG
                         - JPG
        :param fmt: Specifies the format of a temporary output file. When supplied, the filename
                    parameter must be omitted.
        :param toc: Toggles the generation of Table of Contents.
                    Note: currently supported for PDF output only.
        :param pdf_zoom: The zooming to apply when rendering the page to PDF.
        :param pdf_page_size: The page size to use when rendering the page to PDF.
        :param pdf_auto_shrink: Toggles auto-shrinking content to fit the desired page size.
        :param pretty: Toggles pretty printing of the resulting HTML. Not applicable for non-HTML output.
        :return: html filename
        """
        # Ensure that exactly one of filename or fmt is provided
        if filename is None and fmt is None:
            raise ValueError("One of `filename` or `fmt` must be provided.")

        tempdir = tempfile.gettempdir()

        if filename:
            _, fmt_from_name = os.path.splitext(filename)
            # Exclude the dot from the extension, gosh darn it!
            fmt_from_name = fmt_from_name[1:]
            if fmt is None:
                if fmt_from_name == '':
                    raise ValueError('If fmt is not specified, filename must contain extension')
                fmt = fmt_from_name
            else:
                if fmt != fmt_from_name:
                    filename += '.' + fmt
        else:
            name = str_base(abs(hash(self._id))) + "." + fmt
            filename = os.path.join(tempdir, name)

        # Force extension to be lower case so format checks are easier later
        fmt = fmt.lower()

        is_html = "htm" in fmt

        if is_html:
            content = self.render_html(static_output=False, header_block=header_block, footer_block=footer_block)
            html_filename = filename
        else:
            content = self.render_html(static_output=True, pdf_page_size=pdf_page_size)
            name = str_base(abs(hash(self._id))) + ".html"
            html_filename = os.path.join(tempdir, name)

        # File with HTML content is needed either directly or as input for conversion
        with open(html_filename, "w") as f:
            f.write(content)

        if not is_html:

            cmd = ["--no-stop-slow-scripts", "--debug-javascript", "--javascript-delay", str(java_script_delay)]

            if fmt.endswith("pdf"):
                if pdf_page_size is not None:
                    cmd.extend(["--page-size", pdf_page_size])
                cmd.extend(["--orientation", orientation])
                if pdf_zoom != 1:
                    cmd.extend(["--zoom", str(pdf_zoom)])

                if pdf_auto_shrink:
                    cmd.append("--enable-smart-shrinking")
                else:
                    cmd.append("--disable-smart-shrinking")

                if header_block is not None:
                    header_file = str_base(hash(header_block._id)) + ".html"
                    file_path = header_block.publish(os.path.join(tempdir, header_file))
                    cmd += ['--header-html', file_path]
                    cmd += ['--header-spacing', str(header_spacing)]

                if footer_block is not None:
                    footer_file = str_base(hash(footer_block._id)) + ".html"
                    file_path = footer_block.publish(os.path.join(tempdir, footer_file))
                    cmd += ['--footer-html', file_path]
                    cmd += ['--footer-spacing', str(footer_spacing)]

            else:
                # In case the output is an image (not html or pdf), set width to 0
                # so that it fits the content exactly, without any extra margin.
                cmd.extend(["--width", "0"])
            # Add kwargs as additional htmlto... arguments
            [cmd.extend([k, v]) for k, v in kwargs.items()]

            htmlconv(input_file=html_filename, fmt=fmt, toc=toc, tool_args=cmd, output_file=filename)
            return filename

        return html_filename