Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

Is it possible to use PhantomJS's rendering to PDF capabilities when PhantomJS is being used in combination with Selenium and Python? (ie. mimic page.render('file.pdf') behaviour inside Python via Selenium).

I realize that this uses GhostDriver, and GhostDriver doesn't really support much in the way of printing.

If another alternative is possible that isn't Selenium, I'm all ears.

1 Answer

0 votes
by (62.9k points)

Here is a solution using selenium and special command for GhostDriver (it should work since GhostDriver 1.1.0 and PhantomJS 1.9.6, tested with PhantomJS 1.9.8):

#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""Download a webpage as a PDF."""

from selenium import webdriver

def download(driver, target_path):

    """Download the currently displayed page to target_path."""

    def execute(script, args):

        driver.execute('executePhantomScript',

                       {'script': script, 'args': args);

    # hack while the python interface lags

    driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute'

   # set page format

    # inside the execution script, webpage is "this"

    page_format = 'this.paperSize = {format: "A4", orientation: "portrait" };'

    execute(page_format, [])

    # render current page

    render = '''this.render("{}")'''.format(target_path)

    execute(render, [])

if __name__ == '__main__':

    driver = webdriver.PhantomJS('phantomjs')

    driver.get('https://intellipaat.com')

    download(driver, "save_me.pdf")

Browse Categories

...