8

I looking for ability render pdf with PhantomJS via GhostDriver, not just render pdf. When I use next code, then page normally loaded:

from selenium import webdriver

driver = webdriver.PhantomJS('./node_modules/phantomjs/bin/phantomjs')
driver.set_window_size(1024, 768)
driver.get('http://stackoverflow.com')

When I use next script via command line https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js then pdf generated perfectly.

Now I want execute script like rasterize.js (page.render('file.pdf')) but via webdriver. webdriver has execute_script method but it look like PhantomJS code evaluation and do not have access to webpage instance context. Also webdriver has get_screenshot_as_base64 method, but it return only png.

I use latest versions of selenium, phantomjs, nodejs.

So my question how I can get access to PhantomJS webpage instance via GhostDriver and evaluate render method?

Mosam Mehta
  • 1,658
  • 6
  • 25
  • 34
tbicr
  • 24,790
  • 12
  • 81
  • 106
  • I'm looking for this, also... anyone ? – j040p3d20 May 02 '14 at 15:26
  • For just PDF generation (not `GhostDriver` or `WebDriver`) you can use `ghost.py` (need QT), found wrappers with `pyexecjs` or `subprocesses`. Also exists python packages as `pdfkit` and `wkhtmltopdf` as wrappers for `wkhtmltopdf` - it should have same results because also webkit. `weasyprint` also good but not webkit. – tbicr May 02 '14 at 16:05

1 Answers1

9

There is a special way to execute PhantomJS script from GhostDriver, using the next command:

POST /session/id/phantom/execute

It was included in GhostDriver v1.1.0, so it should work since PhantomJS v.1.9.6.

Look at this example:

def execute(script, args):
    driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://stackoverflow.com')

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test.pdf")'''
execute(render, [])

Note that in OS X PhantomJS renders web page as images with not selectable text, due to limitations of Qt rendering engine in OS X (at least with PhantomJS v.1.9.8 and earlier).

MTuner
  • 437
  • 1
  • 6
  • 14
  • And for non-python implementations? Is there a way to do this in Java or any other implementation other than python? – Tibbers Jan 20 '17 at 16:16