logo

Phrender Filter

← Back to Filter List

Phrender


↓ examples

Renders HTML to PNG/PDF using phantom.js. If the HTML relies on local assets such as CSS or image files, these should be specified as inputs.

Aliases for this filter

  • phrender

Converts from file formats:

  • .html
  • .htm
  • .txt

To file formats:

  • .png
  • .pdf

Available settings:

SettingDescriptionDefault
add-new-filesBoolean or list of extensions/patterns to match.True
added-in-versionDexy version when this filter was first available.
additional-doc-filtersFilters to apply to additional documents created as side effects.{}
additional-doc-settingsSettings to apply to additional documents created as side effects.{}
argsArguments to be passed to the executable.
check-return-codeWhether to look for nonzero return code.True
clargsArguments to be passed to the executable (same as 'args').
command-stringThe full command string.%(prog)s %(args)s script.js
data-typeAlias of custom data class to use to store filter output.generic
envDictionary of key-value pairs to be added to environment for runs.{}
examplesTemplates which should be used as examples for this filter.[u'phrender']
exclude-add-new-filesList of patterns to skip even if they match add-new-files.[]
exclude-new-files-from-dirList of directories to skip when adding new files.[]
executableThe executable to be runphantomjs
extFile extension to output.None
extension-mapDictionary mapping input extensions to default output extensions.None
heightHeight of page to capture.768
helpHelpstring for plugin.Renders HTML to PNG/PDF using phantom.js. If the HTML relies on local assets such as CSS or image files, these should be specified as inputs.
initial-timeout10
input-extensionsList of extensions which this filter can accept as input.[u'.html', u'.htm', u'.txt']
keep-originalsWhether, if additional-doc-filters are specified, the original unmodified docs should also be added.False
mkdirA directory which should be created in working dir.None
mkdirsA list of directories which should be created in working dir.[]
nodocWhether filter should be excluded from documentation.False
outputWhether to output results of this filter by default by reporters such as 'output' or 'website'.False
output-extensionsList of extensions which this filter can produce as output.[u'.png', u'.pdf']
override-workspace-exclude-filtersIf True, document will be populated to other workspaces ignoring workspace-exclude-filters.False
path-extensionsstrings to extend path with[]
preserve-prior-data-classWhether output data class should be set to match the input data class.False
record-varsWhether to add code that will automatically record values of variables.False
require-outputShould dexy raise an exception if no output is produced by this filter?True
scriptargsArguments to be passed to the executable.
tagsTags which describe the filter.[]
timeout10
use-wdWhether to use a custom working directory when running filter.True
variablesA dictionary of variable names and values to make available to this filter.{}
varsA dictionary of variable names and values to make available to this filter.{}
version-commandCommand to call to return version of installed software.phantomjs --version
widthWidth of page to capture.1024
windows-version-commandCommand to call on windows to return version of installed software.None
workspace-exclude-filtersFilters whose output should be excluded from workspace.[u'pyg']
workspace-includesIf set to a list of filenames or extensions, only these will be populated to working dir.None
write-stderr-to-stdoutShould stderr be piped to stdout?True

phrender Filter

The phrender filter uses phantom.js to render HTML content to an image.

Here is some HTML:

<html>
    <head>
    </head>
    <body>
        <div style="border: thin solid blue; width: 100px;">
            <p>hello!</p>
        </div>
    </body>
</html>

Here is how we specify this:

- page.html|phrender:
    - phrender: { width : 200, height: 200 }

Here is the PNG image generated by phrender:

page.png
Filter Source Code
class PhantomJsRenderSubprocessFilter(SubprocessFilter):
    """
    Renders HTML to PNG/PDF using phantom.js.
    
    If the HTML relies on local assets such as CSS or image files, these should
    be specified as inputs.
    """
    aliases = ['phrender']
    _settings = {
            'add-new-files' : True,
            'examples' : ['phrender'],
            'executable' :  'phantomjs',
            "width" : ("Width of page to capture.", 1024),
            "height" : ("Height of page to capture.", 768),
            'version-command' : 'phantomjs --version',
            'command-string' : "%(prog)s %(args)s script.js",
            'input-extensions' : [".html", ".htm", ".txt"],
            'output-extensions' : [".png", ".pdf"]
            }

    def custom_populate_workspace(self):
        width = self.setting('width')
        height = self.setting('height')

        timeout = self.setup_timeout()
        if not timeout:
            raise Exception("must have timeout")

        args = {
                'address' : self.work_input_filename(),
                'output' : self.work_output_filename(),
                'width' : width,
                'height' : height,
                'timeout' : timeout
                }

        js = """
        address = '%(address)s'
        output = '%(output)s'
        var page = new WebPage(),
            address, output, size;

        page.viewportSize = { width: %(width)s, height: %(height)s };
        page.open(address, function (status) {
            if (status !== 'success') {
                console.log('Unable to load the address!');
            } else {
                window.setTimeout(function () {
                page.render(output);
                phantom.exit();
                }, %(timeout)s);
            }
        });
        """ % args

        wd = self.parent_work_dir()
        scriptfile = os.path.join(wd, "script.js")
        self.log_debug("scriptfile: %s" % scriptfile)
        self.log_debug("js for scriptfile: %s" % js)
        with open(scriptfile, "w") as f:
            f.write(js)

Content © 2013 Dr. Ana Nelson | Site Design © Copyright 2011 Andre Gagnon | All Rights Reserved.