• This repository has been archived on 16/Aug/2021
  • Stars
    star
    204
  • Rank 185,261 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PhantomJS screenshotting done right

url-to-image

DEPRECATED: I recommend using implementations that use Headless Chrome underneath, for example: https://github.com/kimmobrunfeldt/squint or https://github.com/alvarcarto/url-to-pdf-api. You can still continue using this module but no updates will be applied.

Build Status Dependency Status devDependency Status

Takes screenshot of a given page. This module correctly handles pages which dynamically load content making AJAX requests. Instead of waiting fixed amount of time before rendering, we give a short time for the page to make additional requests.

Usage from code:

const urlToImage = require('url-to-image');
urlToImage('http://google.com', 'google.png').then(function() {
    // now google.png exists and contains screenshot of google.com
}).catch(function(err) {
    console.error(err);
});

Usage from command line:

$ urltoimage http://google.com google.png

Sometimes it's useful to see requests, responses and page errors from PhantomJS:

$ urltoimage http://google.com google.png --verbose
-> GET http://google.com/
-> GET http://www.google.fi/?gfe_rd=cr&ei=xTYxVouuOeiA8QexyZ2QBw
<- 302 http://google.com/
-> GET http://ssl.gstatic.com/gb/images/b_8d5afc09.png

... quite a lot of requests ...

-> GET http://ssl.gstatic.com/gb/js/sem_32d9c4210965b8e7bfa34fa376864ce8.js
<- 200 http://ssl.gstatic.com/gb/js/sem_32d9c4210965b8e7bfa34fa376864ce8.js
Render screenshot..
Done.

For more options, see CLI chapter.

Install

npm install url-to-image

PhantomJS is installed by using Medium/phantomjs NPM module.

API

const urlToImage = require('url-to-image');

urlToImage(url, filePath, options)

This will run a PhantomJS script(url-to-image.js) which renders given url to an image.

Parameters

  • url Url of the page which will be rendered as image. For example http://google.com.

  • filePath File path where to save rendered image.

  • options Options for page rendering.

    Default values for options

    {
        // User agent width
        width: 1200,
    
        // User agent height
        height: 800,
    	
    	// The file type of the rendered image. By default, PhantomJS 
    	// sets the output format automatically based on the file extension.
    	// Supported: PNG, GIF, JPEG, PDF
    	fileType: 'jpeg',
    	
    	// The file quality of the rendered image, represented as a percentage. 
    	// This reduces the image size. By default, 100 percent is used.
    	fileQuality: 100,
    	
    	// Sets the width of the final image (cropped from the User agent defined size)
    	// By default, no cropping is done.
    	cropWidth: false,
    	
    	// Sets the height of the final image (cropped from the User agent defined size)
    	// By default, no cropping is done.
    	cropHeight: false,
    	
    	//Sets the offset of where to begin the image cropping from the left margin 
    	// of the page
    	cropOffsetLeft: 0,
    
    	//Sets the offset of where to begin the image cropping from the top margin 
    	// of the page
    	cropOffsetTop: 0,
    
        // How long in ms do we wait for additional requests
        // after all initial requests have gotten their response
        // Note: this does NOT limit the amount of time individual request
        //       can take in time
        requestTimeout: 300,
    
        // How long in ms do we wait at maximum. The screenshot is
        // taken after this time even though resources are not loaded
        maxTimeout: 1000 * 10,
    
        // How long in ms do we wait for phantomjs process to finish.
        // If the process is running after this time, it is killed.
        killTimeout: 1000 * 60 * 2,
    
        // If true, phantomjs script will output requests and responses to stdout
        verbose: false,
    
        // String of of phantomjs arguments
        // You can separate arguments with spaces
        // See options in http://phantomjs.org/api/command-line.html
        phantomArguments: '--ignore-ssl-errors=true'
    }

Returns

Bluebird promise object.

Detailed example

const urlToImage = require('url-to-image');

const options = {
    width: 600,
    height: 800,
    // Give a short time to load additional resources
    requestTimeout: 100
}

urlToImage('http://google.com', 'google.png', options)
.then(function() {
    // do stuff with google.png
})
.catch(function(err) {
    console.error(err);
});

Command line interface (CLI)

The package also ships with a cli called urltoimage.

Usage: urltoimage <url> <path> [options]

<url>   Url to take screenshot of
<path>  File path where the screenshot is saved


Options:
  --width              Width of the viewport            [string] [default: 1280]
  --height             Height of the viewport            [string] [default: 800]
  --file-type          The file type of the rendered image. By default, 
		               PhantomJS sets the output format automatically based on 
					   the file extension. Supported: PNG, GIF, JPEG, PDF
					                                   [string] [default: false]
  --file-quality       The file quality of the rendered image, represented as a 
                       percentage. This reduces the image size. 
					   By default, 100 percent is used.
					                                     [string] [default: 100]
  --crop-width         Sets the width of the final image (cropped from the User 
                       agent defined size).
					                                   [string] [default: false]
  --crop-height        Sets the height of the final image (cropped from the User 
                       agent defined size).
					                                   [string] [default: false]
  --cropoffset-left    Sets the offset of where to begin the image cropping from 
                       the left margin of the page.
					                                   [string] [default: false]
  --cropoffset-top     Sets the offset of where to begin the image cropping from 
                       the top margin of the page.
					                                   [string] [default: false]
  --request-timeout    How long in ms do we wait for additional requests after
                       all initial requests have gotten their response
                                                         [string] [default: 300]
  --max-timeout        How long in ms do we wait at maximum. The screenshot is
                       taken after this time even though resources are not
                       loaded                          [string] [default: 10000]
  --kill-timeout       How long in ms do we wait for phantomjs process to
                       finish. If the process is running after this time, it is
                       killed.                        [string] [default: 120000]
  --phantom-arguments  Command line arguments to be passed to phantomjs
                       process.You must use the format
                       --phantom-arguments="--version".
                                  [string] [default: "--ignore-ssl-errors=true"]
  --verbose            If set, script will output additional information to
                       stdout.                        [boolean] [default: false]
  -h, --help           Show help                                       [boolean]
  -v, --version        Show version number                             [boolean]

Examples:
  urltoimage http://google.com google.png

Contributors

Release

  • Commit all changes.

  • Use releasor to automate the release:

    releasor --bump patch

  • Edit GitHub release notes.

Test

npm test

Attribution

This module was inspired by

License

MIT

More Repositories

1

progressbar.js

Responsive and slick progress bars
JavaScript
7,755
star
2

git-hours

Estimate time spent on a git repository
JavaScript
730
star
3

react-progressbar.js

Responsive and slick progress bars for React.
JavaScript
310
star
4

eink-weather-display

Battery-powered E-Ink weather display for our home.
C
252
star
5

howto-everything

Collection of notes and howtos. Questions / ideas -> please open an issue :) Also check my blog:
Shell
153
star
6

football-score-detector

Detect table football score from camera image with machine vision
Python
68
star
7

dont-copy-paste-this-frontend-template

Frontend template project to get you started with frontend development
JavaScript
55
star
8

express-example

Example of good Express.js architecture with Promises and nice error handling
JavaScript
55
star
9

nap

Convenient way to request HTTP APIs
Python
42
star
10

v8-profiler-trigger

Trigger CPU profile recording or heap snapshots for node apps using keyboard shortcuts.
JavaScript
28
star
11

squint

Makes visual reviews of web app releases easy.
TypeScript
26
star
12

releasor

Command line tool to automate node module releasing to NPM and Git
JavaScript
23
star
13

fix-outline

*:focus { outline: none } done right.
JavaScript
18
star
14

spawn-default-shell

Spawn shell command with platform default shell
JavaScript
12
star
15

ppmusicbot

Telegram bot which adds all linked Spotify track links to a shared playlist
JavaScript
8
star
16

dcr

Node CLI tool to decrypt partially encrypted log streams on the fly
JavaScript
8
star
17

iphone-x

Testing webgl. Based on https://github.com/PavelDoGreat/WebGL-Fluid-Simulation/
JavaScript
7
star
18

html5-pathfinder

Visualisation of path finding with canvas
JavaScript
7
star
19

promise-retryify

Add retry functionality to any Promise based library
JavaScript
6
star
20

shary.in

Mobile pastebin for images
JavaScript
5
star
21

blog

Personal blog at kimmo.blog
TypeScript
4
star
22

egtest

Test example code blocks in documentation
Python
4
star
23

rate-limiting-s3-proxy

Pass-through S3 proxy with rate limiting.
JavaScript
4
star
24

busse-release

Web version of real time bus tracking system in Tampere
JavaScript
4
star
25

concurrently

Moved under github.com/open-cli-tools/concurrently
4
star
26

labyrinth

Online version of the Labyrinth board game. The game server runs on the host's browser and networking happens peer-to-peer.
TypeScript
4
star
27

pair-coding-with-chatgpt

I paired up with ChatGPT to code a poker game with react
HTML
3
star
28

array-sort-compare

Generic type-aware compare function for Array.prototype.sort() and sortDeep.
JavaScript
3
star
29

kauko

Kauko is remote control for computer.
Python
3
star
30

shoot

UI review for web applications
JavaScript
3
star
31

bluetooth-web-api-talk

JavaScript
3
star
32

elegant-clock

Elegant analog clock
JavaScript
3
star
33

busse-web

Public transit real time on a map.
JavaScript
3
star
34

planter-docker

Dockerfile that packages planter and plantuml into a Docker image
Shell
3
star
35

lissu-proxy

Nicer JSON API for lissu.tampere.fi
JavaScript
3
star
36

service-worker-demo

Tiny demo of Service Worker
JavaScript
2
star
37

presentic

Impress your audience
JavaScript
2
star
38

drydoc

DRY documents
Python
1
star
39

random_python_utils

collection of snippets and functions
Python
1
star
40

mips-asm-calculator

Calculator
Assembly
1
star
41

arr-uniq

Generic array uniq function which supports equals predicate function
JavaScript
1
star
42

ocr-engine

Experimental OCR engine
Python
1
star
43

wave

Experimenting with canvas and paper.js
JavaScript
1
star
44

chokidar-cli

Moved to github.com/open-cli-tools/chokidar-cli
1
star
45

arr-mutations

Calculate all mutation operations between two arrays. Supports a generic equals predicate function
JavaScript
1
star
46

text-to-speech-hubot

JavaScript
1
star
47

how-much-oss-projects-are-worth-in-cash

How much open source projects are worth in cash.
JavaScript
1
star
48

busse-api

Busse API for all cities.
JavaScript
1
star
49

entangle

Screen share using Chrome without any installations or plugins.
JavaScript
1
star
50

react-scripts-antd

Fork of react-scripts to be used with http://ant.design
JavaScript
1
star
51

mozart

Convert any given text to music
JavaScript
1
star
52

tencalendar

Incredibly fast calendar for power users
JavaScript
1
star
53

portal

Real life portal controlled with Leap Motion
JavaScript
1
star
54

lodash-merge-pollution-example

Demonstration of _.merge prototype pollution vulnerability
JavaScript
1
star