/
webshot
executable file
·102 lines (78 loc) · 2.48 KB
/
webshot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env perl
use common::sense;
use Gtk3 -init;
use Gtk3::WebKit;
use List::Util 'max';
use Getopt::Long;
sub usage {
print <<END;
Usage: webshot [options] URI [out.png]
Options:
-h|--height Height of the browser windown. If not specified
the window will be resized in order for HTML
document to fit inside
-w|--width Width of the window
-s|--scale If specified the resulting image will be scaled
to have this width, aspect ratio will be preserved
(Image::Magick is required)
-t|--thumb Filename to save scaled image. If not specified the
output will be replaced
-v|--verbose Print error messages from the browser while
processing the page
--help This help
END
exit(0);
}
my ($height,$width,$scale,$thumb,$verbose);
GetOptions(
'height=i'=> \$height,
'width=i' => \$width,
'scale=i' => \$scale,
'thumb=s' => \$thumb,
'verbose!'=> \$verbose,
'help' => \&usage
);
my $url = shift @ARGV || usage();
my $out = shift @ARGV || 'out.png';
unless ($verbose){
open STDERR, '>', '/dev/null';
}
my $window = Gtk3::OffscreenWindow->new('toplevel');
$window->set_default_size($width||1024, $height||768);
$window->signal_connect(destroy => sub { Gtk3->main_quit() });
# Create a WebKit widget
my $view = Gtk3::WebKit::WebView->new();
# Load a page
$view->load_uri($url);
# Pack the widgets together
my $scrolls = Gtk3::ScrolledWindow->new();
$scrolls->add($view);
$window->add($scrolls);
$window->show_all();
# load and draw
Gtk3->main_iteration while Gtk3->events_pending or $view->get_load_status ne 'finished';
unless ($height) {
# find content height
my $html = $view->get_dom_document->get_document_element;
$height = max( $html->get_client_height, $html->get_scroll_height, $html->get_offset_height );
# resize window
$window->set_default_size($width||1024, $height);
Gtk3->main_iteration while Gtk3->events_pending;
}
$window->get_surface()->write_to_png($out);
if ($scale) {
require Image::Magick;
my $img = new Image::Magick;
$width ||= 1024;
$height *= $scale/$width;
$width = $scale;
$img->Read($out);
$img->Resize(
width => $width,
height => $height,
filter => 'Lagrange'
);
$img->Set( density => $width.'x'.$height );
$img->Set( quality => '85' );
$img->Write( filename => ($thumb||$out));
}