Debian Codegraph @

bin/crunchjpgs.pl

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 #!/usr/bin/perl -w
2
3 package main;
4
5 use warnings;
6 use strict;
7 use CAM::PDF;
8 use Getopt::Long;
9 use Pod::Usage;
10 use English qw(-no_match_vars);
11
12 our $VERSION = '1.60';
13
14 my %opts = (
15 # Hardcoded:
16 template => '/usr/share/libcam-pdf-perl/crunchjpg_tmpl.pdf',
17
18 # User settable values:
19 justjpgs => 0,
20 quality => 50,
21 scale => undef,
22 scalemin => 0,
23 skip => {},
24 only => {},
25 Verbose => 0,
26 verbose => 0,
27 order => 0,
28 help => 0,
29 version => 0,
30
31 # Temporary values:
32 onlyval => [],
33 skipval => [],
34 qualityval => undef,
35 scaleminval=> undef,
36 scaleval => undef,
37 scales => {1 => undef, 2 => '50%', 4 => '25%', 8 => '12.5%'},
38 );
39
40 Getopt::Long::Configure('bundling');
41 GetOptions('S|skip=s' => \@{$opts{skipval}},
42 'O|only=s' => \@{$opts{onlyval}},
43 'q|quality=i' => \$opts{qualityval},
44 's|scale=i' => \$opts{scaleval},
45 'm|scalemin=i' => \$opts{scaleminval},
46 'j|justjpgs' => \$opts{justjpgs},
47 'veryverbose' => \$opts{Verbose},
48 'v|verbose' => \$opts{verbose},
49 'o|order' => \$opts{order},
50 'h|help' => \$opts{help},
51 'V|version' => \$opts{version},
52 ) or pod2usage(1);
53 if ($opts{help})
54 {
55 pod2usage(-exitstatus => 0, -verbose => 2);
56 }
57 if ($opts{version})
58 {
59 print "CAM::PDF v$CAM::PDF::VERSION\n";
60 exit 0;
61 }
62
63 ## Fix up and validate special options:
64
65 if ($opts{Verbose})
66 {
67 $opts{verbose} = 1;
68 }
69 if (defined $opts{scaleval})
70 {
71 if (exists $opts{scales}->{$opts{scaleval}})
72 {
73 $opts{scale} = $opts{scales}->{$opts{scaleval}};
74 }
75 else
76 {
77 die "Invalid value for --scale switch\n";
78 }
79 }
80 if (defined $opts{scaleminval})
81 {
82 if ($opts{scaleminval} =~ m/\A\d+\z/xms && $opts{scaleminval} > 0)
83 {
84 $opts{scalemin} = $opts{scaleminval};
85 }
86 else
87 {
88 die "Invalid value for --scalemin switch\n";
89 }
90 }
91 if (defined $opts{qualityval})
92 {
93 if ($opts{qualityval} =~ m/\A\d+\z/xms && $opts{qualityval} >= 1 && $opts{qualityval} <= 100)
94 {
95 $opts{quality} = $opts{qualityval};
96 }
97 else
98 {
99 die "The JPEG --quality setting must be between 1 and 100\n";
100 }
101 }
102 foreach my $flag (qw( skip only ))
103 {
104 foreach my $val (@{$opts{$flag.'val'}})
105 {
106 foreach my $key (split /\D+/xms, $val)
107 {
108 $opts{$flag}->{$key} = 1;
109 }
110 }
111 }
112 if (!-f $opts{template})
113 {
114 die "Cannot find the template pdf called $opts{template}\n";
115 }
116
117 # Start work:
118
119 if (@ARGV < 1)
120 {
121 pod2usage(1);
122 }
123
124 my $infile = shift;
125 my $outfile = shift || q{-};
126
127 my $doc = CAM::PDF->new($infile) || die "$CAM::PDF::errstr\n";
128
129 if (!$doc->canModify())
130 {
131 die "This PDF forbids modification\n";
132 }
133
134 my $pages = $doc->numPages();
135 my $nimages = 0;
136 my $rimages = 0;
137
138 my %doneobjs;
139
140 my $oldcontentsize = $doc->{contentlength};
141 my $oldtotsize = 0;
142 my $newtotsize = 0;
143
144 for my $p (1..$pages)
145 {
146 my $c = $doc->getPageContent($p);
147 my @parts = split /(\/[\w]+\s*Do)\b/xms, $c;
148 foreach my $part (@parts)
149 {
150 if ($part =~ m/\A(\/[\w]+)\s*Do\z/xms)
151 {
152 my $ref = $1;
153 my $xobj = $doc->dereference($ref, $p);
154 my $objnum = $xobj->{objnum};
155 my $im = $doc->getValue($xobj);
156 my $l = $im->{Length} || $im->{L} || 0;
157 if ($l)
158 {
159 $l = $doc->getValue($l);
160 }
161 my $w = $im->{Width} || $im->{W} || 0;
162 if ($w)
163 {
164 $w = $doc->getValue($w);
165 }
166 my $h = $im->{Height} || $im->{H} || 0;
167 if ($h)
168 {
169 $h = $doc->getValue($h);
170 }
171
172 next if (exists $doneobjs{$objnum});
173
174 $nimages++;
175 _inform("Image $nimages page $p, $ref = object $objnum, (w,h)=($w,$h), length $l", $opts{verbose});
176
177 if (exists $opts{skip}->{$objnum} ||
178 (0 < scalar keys %{$opts{only}} && !exists $opts{only}->{$objnum}))
179 {
180 _inform("Skipping object $objnum", $opts{verbose});
181 next;
182 }
183
184 my $isjpg = _isjpg($im);
185
186 if ((!$isjpg) && $opts{justjpgs})
187 {
188 _inform('Not a jpeg', $opts{verbose});
189 }
190 else
191 {
192 my $oldsize = $doc->getValue($im->{Length});
193 if (!$oldsize)
194 {
195 die "PDF error: Failed to get size of image\n";
196 }
197 $oldtotsize += $oldsize;
198
199 my $tmpl = CAM::PDF->new($opts{template}) || die "$CAM::PDF::errstr\n";
200
201 # Get a handle on the needed data bits from the template
202 my $media_array = $tmpl->getValue($tmpl->getPage(1)->{MediaBox});
203 my $rawpage = $tmpl->getPageContent(1);
204
205 $media_array->[2]->{value} = $w;
206 $media_array->[3]->{value} = $h;
207 my $page = $rawpage;
208 $page =~ s/xxx/$w/igxms;
209 $page =~ s/yyy/$h/igxms;
210 $tmpl->setPageContent(1, $page);
211 $tmpl->replaceObject(9, $doc, $objnum, 1);
212
213 my $ofile = "/tmp/crunchjpg.$$";
214 $tmpl->cleanoutput($ofile);
215
216 my $cmd = ('convert ' .
217 ($opts{scale} && $w > $opts{scalemin} && $h > $opts{scalemin} ?
218 "-scale '$opts{scale}' " : q{}) .
219 "-quality $opts{quality} " .
220 '-density 72x72 ' .
221 "-page ${w}x$h " .
222 "pdf:$ofile jpg:- | " .
223 'convert jpg:- pdf:- |');
224
225 _inform($cmd, $opts{Verbose});
226
227 # TODO: this should use IPC::Open3 or the like
228 open my $pipe, $cmd ## no critic (ProhibitTwoArgOpen)
229 or die "Failed to convert object $objnum to a jpg and back\n";
230 my $content = do { local $RS = undef; <$pipe>; };
231 close $pipe
232 or die "Failed to convert object $objnum to a jpg and back\n";
233
234 my $jpg = CAM::PDF->new($content) || die "$CAM::PDF::errstr\n";
235 my $jpgim = $jpg->getObjValue(8);
236 my $jpgsize = $jpg->getValue($jpgim->{Length});
237
238 if ($jpgsize < $oldsize) {
239 $doc->replaceObject($objnum, $jpg, 8, 1);
240
241 $newtotsize += $jpgsize;
242
243 my $percent = sprintf '%.1f', 100 * ($oldsize - $jpgsize) / $oldsize;
244 _inform("\tcompressed $oldsize -> $jpgsize ($percent%)", $opts{verbose});
245 $doneobjs{$objnum} = 1;
246 $rimages++;
247 } else {
248 _inform("\tskipped $oldsize -> $jpgsize", $opts{verbose});
249 }
250
251 }
252 }
253 }
254 }
255
256 _inform("Crunched $rimages of $nimages images", $opts{verbose});
257 $doc->cleanoutput($outfile);
258
259 my $newcontentsize = $doc->{contentlength};
260
261 if ($opts{verbose})
262 {
263 my $contentpercent = sprintf '%.1f', $oldcontentsize ? 100 * ($oldcontentsize - $newcontentsize) / $oldcontentsize : 0;
264 my $totpercent = sprintf '%.1f', $oldtotsize ? 100 * ($oldtotsize - $newtotsize) / $oldtotsize : 0;
265 _inform('Compression summary:', 1);
266 _inform(" Document: $oldcontentsize -> $newcontentsize ($contentpercent%)", 1);
267 _inform(" Images: $oldtotsize -> $newtotsize ($totpercent%)", 1);
268 }
269
270 sub _isjpg
271 {
272 my $im = shift;
273 return if (!$im->{Filter});
274
275 my $f = $im->{Filter};
276 my @names = $f->{type} eq 'array' ? @{$f->{value}} : $f;
277 for my $e (@names)
278 {
279 my $name = $doc->getValue($e);
280 if (ref $name)
281 {
282 $name = $name->{value};
283 }
284 #warn "Checking $name\n";
285 if ($name eq 'DCTDecode')
286 {
287 return 1;
288 }
289 }
290 return;
291 }
292
293 sub _inform
294 {
295 my $str = shift;
296 my $verbose = shift;
297
298 if ($verbose)
299 {
300 print STDERR $str, "\n";
301 }
302 return;
303 }
304
305 __END__
306
307 =for stopwords crunchjpgs.pl ImageMagick JPG rescaling
308
309 =head1 NAME
310
311 crunchjpgs.pl - Compress all JPG images in a PDF
312
313 =head1 SYNOPSIS
314
315 crunchjpgs.pl [options] infile.pdf [outfile.pdf]
316
317 Options:
318 -j --justjpgs make script skip non-JPGs
319 -q --quality select JPG output quality (default 50)
320 -s --scale=num select a rescaling factor for the JPGs (default 100%)
321 -m --scalemin=size don't scale JPGs smaller than this pixel size (width or height)
322 -O --only=imnum only change the specified images (can be used mutliple times)
323 -S --skip=imnum don't change the specified images (can be used mutliple times)
324 -o --order preserve the internal PDF ordering for output
325 --veryverbose increases the verbosity
326 -v --verbose print diagnostic messages
327 -h --help verbose help message
328 -V --version print CAM::PDF version
329
330 The available values for --scale are:
331
332 1 100%
333 2 50%
334 4 25%
335 8 12.5%
336
337 C<imnum> is a comma-separated list of integers indicating the images
338 in order that they appear in the PDF. Use F<listimages.pl> to retrieve
339 the image numbers.
340
341 =head1 DESCRIPTION
342
343 Requires the ImageMagick B<convert> program to be available
344
345 Tweak all of the JPG images embedded in a PDF to reduce their size.
346 This reduction can come from increasing the compression and/or
347 rescaling the whole image. Various options give you full control over
348 which images are altered.
349
350 =head1 SEE ALSO
351
352 CAM::PDF
353
354 F<listimages.pl>
355
356 F<extractallimages.pl>
357
358 F<extractjpgs.pl>
359
360 F<uninlinepdfimages.pl>
361
362 =head1 AUTHOR
363
364 See L<CAM::PDF>
365
366 =cut