PDFUtils.pm

filter: Statementstmt 16.4% 38 / 231 Branchbran 0.0% 0 / 100 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 46.6% 7 / 15 Podpod 100% 6 / 6 totaltotal 13.0% 51 / 391 CC 64 SCAR 52.5
CC
64
Cov
11%
convert_pdf_to_text
462.0
remove_pdf_password
156.0
add_pdf_password
110.0
CRAP 190.8
↑ Summary pdfgrep.pm »
1 package App::PDFUtils;
2  
3 1 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Log::ger;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use File::chdir;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Perinci::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
12 1 our $DATE = '2026-06-27'; # DATE
13 1 our $DIST = 'App-PDFUtils'; # DIST
14 1 our $VERSION = '0.019'; # VERSION
15  
16 1 our %SPEC;
17  
18 my %argspec0_files = (
19 files => {
20 schema => ['array*', of=>'filename*', min_len=>1,
21 #uniq=>1, # not yet implemented by Data::Sah
22 ],
23 req => 1,
24 pos => 0,
25 slurpy => 1,
26 0 ▶ 'x.element_completion' => [filename => {filter => sub { /\.pdf$/i }}],
Subroutine __ANON__: not called CC=1 SCAR=1.2
27 },
28 );
29  
30 our %argspec0_file = (
31 file => {
32 summary => 'Input file',
33 schema => ['filename*'],
34 req => 1,
35 pos => 0,
36 0 ▶ 'x.completion' => [filename => {filter => sub { /\.pdf$/i }}],
Subroutine __ANON__: not called CC=1 SCAR=1.2
37 },
38 );
39  
40 1 our %argspecopt_quiet = (
41 quiet => {
42 schema => ['bool*'],
43 cmdline_aliases => {q=>{}},
44 },
45 );
46  
47 1 our %argspecopt1_output = (
48 output => {
49 summary => 'Output path',
50 schema => ['filename*'],
51 pos => 1,
52 },
53 );
54  
55 1 our %argspecopt_overwrite = (
56 overwrite => {
57 schema => 'bool*',
58 cmdline_aliases => {O=>{}},
59 },
60 );
61  
62 1 our %argspecopt_return_output_file = (
63 return_output_file => {
64 summary => 'Return the path of output file instead',
65 schema => 'bool*',
66 description => <<'MARKDOWN',
67  
68 This is useful when you do not specify an output file but do not want to show
69 the converted document to stdout, but instead want to get the path to a
70 temporary output file.
71  
72 MARKDOWN
73 },
74 );
75  
76 $SPEC{add_pdf_password} = {
77 1 v => 1.1,
78 summary => 'Password-protect PDF files',
79 description => <<'MARKDOWN',
80  
81 This program is a wrapper for <prog:qpdf> to password-protect PDF files
82 (in-place). This is the counterpart for <prog:remove-pdf-password>. Why use this
83 wrapper instead of **qpdf** directly? This wrapper offers configuration file
84 support, where you can put the password(s) you want to use there. The wrapper
85 also offers multiple file support and additional options, e.g. whether to create
86 backup.
87  
88 MARKDOWN
89 args => {
90 %argspec0_files,
91 password => {
92 schema => ['str*', min_len=>1],
93 req => 1,
94 },
95 backup => {
96 summary => 'Whether to backup the original file to ORIG~',
97 schema => 'bool*',
98 default => 1,
99 },
100 # XXX key_length (see qpdf, but when 256 can't be opened by evince)
101 # XXX other options (see qpdf)
102 },
103 deps => {
104 prog => 'qpdf',
105 },
106 links => [
107 {url => 'prog:remove-pdf-password'},
108 ],
109 };
110 0 ▶sub add_pdf_password {
Subroutine add_pdf_password: not called CC=10 SCAR=47.0
Pod documented
111 #require File::Temp;
112 0 require IPC::System::Options;
113 #require Proc::ChildError;
114 #require Path::Tiny;
115  
116 0 my %args = @_;
117  
118 0 my $envres = envresmulti();
119  
120 FILE:
121 0 for my $f (@{ $args{files} }) {
122 0 ▶ unless (-f $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $f) 0 0 0
123 0 $envres->add_result(404, "File not found", {item_id=>$f});
124 0 next FILE;
125 }
126 # XXX test that tempfile doesn't yet exist. but actually we can't avoid
127 # race condition because qpdf is another process
128 0 (my $tempf = $f) =~ s/\.pdf$/".tmp_" . int(rand()*900_000 + 100_000) . ".pdf"/ei
129 0 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
(my $tempf = $f) =~ s/\.pdf$/'.tmp_' . int((rand()) * 900000 + 100000) . '.pdf';/ie or do { $envres->add_result(412, "Cannot set temporary name for $f"); next FILE } 0 0 0
130 0 $envres->add_result(412, "Cannot set temporary name for $f");
131 0 next FILE;
132 };
133  
134 0 my $decrypted;
135 0 my ($stdout, $stderr);
136 IPC::System::Options::system(
137 {log => 1, capture_stdout => \$stdout, capture_stderr => \$stderr},
138 0 "qpdf", "--encrypt", $args{password}, $args{password}, 128, "--", $f, $tempf);
139 0 my $err = $?;# ? Proc::ChildError::explain_child_error() : '';
140 0 ▶ if ($err && $stderr =~ /: invalid password$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($err and $stderr =~ /: invalid password$/) { } 0 0 0
elsif ($err) { } 0 0 0
Condition0%0/3
$err and $stderr =~ /: invalid password$/
!ll&&!rl&&r
000
MC/DC0%0/2
$err and $stderr =~ /: invalid password$/
$err $stderr =~ /: invalid password$/
Truth table0%0/3
A and B
A= $errB= $stderr =~ /: invalid password$/
ABresult
0X0
100
111
141 0 $envres->add_result(412, "File already encrypted", {item_id=>$f});
142 0 next FILE;
143 } elsif ($err) {
144 0 $stderr =~ s/\R//g;
145 0 $envres->add_result(500, $stderr, {item_id=>$f});
146 0 next FILE;
147 }
148  
149 BACKUP:
150 {
151 0 ▶ last unless $args{backup};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"backup"} 0 0 0
152 0 ▶ unless (rename $f, "$f~") {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $f, "$f~") 0 0 0
153 0 warn "Can't backup original '$f' to '$f~': $!, skipped backup\n";
154 0 last;
155 };
156 }
157 0 ▶ unless (rename $tempf, $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $tempf, $f) 0 0 0
158 0 $envres->add_result(500, "Can't rename $tempf to $f: $!", {item_id=>$f});
159 0 next FILE;
160 }
161 0 $envres->add_result(200, "OK", {item_id=>$f});
162 }
163  
164 0 $envres->as_struct;
165 }
166  
167 $SPEC{remove_pdf_password} = {
168 1 v => 1.1,
169 summary => 'Remove password from PDF files',
170 description => <<'MARKDOWN',
171  
172 This program is a wrapper for <prog:qpdf> to remove passwords from PDF files
173 (in-place).
174  
175 The motivation for this wrapper is the increasing occurence of financial
176 institutions sending financial statements or documents in the format of
177 password-protected PDF file. This is annoying when we want to archive the file
178 or use it in an organization because we have to remember different passwords for
179 different financial institutions and re-enter the password everytime we want to
180 use the file. (The banks could've sent the PDF in a password-protected .zip, or
181 use PGP-encrypted email, but I digress.)
182  
183 Compared to using **qpdf** directly, this wrapper offers some additional
184 features/options and convenience, for example: multiple file support, multiple
185 password matching attempt, configuration file, option whether you want backup,
186 etc.
187  
188 You can provide the passwords to be tried in a configuration file,
189 `~/remove-pdf-password.conf`, e.g.:
190  
191 passwords = pass1
192 passwords = pass2
193 passwords = pass3
194  
195 or:
196  
197 passwords = ["pass1", "pass2", "pass3"]
198  
199 MARKDOWN
200 args => {
201 %argspec0_files,
202 passwords => {
203 schema => ['array*', of=>['str*', min_len=>1], min_len=>1],
204 },
205 backup => {
206 summary => 'Whether to backup the original file to ORIG~',
207 schema => 'bool*',
208 default => 1,
209 },
210 },
211 deps => {
212 prog => 'qpdf',
213 },
214 links => [
215 {url => 'prog:add-pdf-password'},
216 ],
217 };
218 0 ▶sub remove_pdf_password {
Subroutine remove_pdf_password: not called CC=12 SCAR=50.5
Pod documented
219 #require File::Temp;
220 0 require IPC::System::Options;
221 #require Proc::ChildError;
222 #require Path::Tiny;
223  
224 0 my %args = @_;
225  
226 0 my $envres = envresmulti();
227  
228 FILE:
229 0 for my $f (@{ $args{files} }) {
230 0 ▶ unless (-f $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $f) 0 0 0
231 0 $envres->add_result(404, "File not found", {item_id=>$f});
232 0 next FILE;
233 }
234 # XXX test that tempfile doesn't yet exist. but actually we can't avoid
235 # race condition because qpdf is another process
236 0 (my $tempf = $f) =~ s/\.pdf$/".tmp_" . int(rand()*900_000 + 100_000) . ".pdf"/ei
237 0 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
(my $tempf = $f) =~ s/\.pdf$/'.tmp_' . int((rand()) * 900000 + 100000) . '.pdf';/ie or do { $envres->add_result(412, "Cannot set temporary name for $f"); next FILE } 0 0 0
238 0 $envres->add_result(412, "Cannot set temporary name for $f");
239 0 next FILE;
240 };
241  
242 0 my $decrypted;
243 PASSWORD:
244 0 for my $p (@{ $args{passwords} }) {
245 0 my ($stdout, $stderr);
246 0 IPC::System::Options::system(
247 {log => 1, fail_log_level => 'info', capture_stdout => \$stdout, capture_stderr => \$stderr},
248 "qpdf", "--password=$p", "--decrypt", $f, $tempf);
249 0 my $err = $?;# ? Proc::ChildError::explain_child_error() : '';
250 0 ▶ if ($err && $stderr =~ /: invalid password$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($err and $stderr =~ /: invalid password$/) { } 0 0 0
elsif ($err) { } 0 0 0
Condition0%0/3
$err and $stderr =~ /: invalid password$/
!ll&&!rl&&r
000
MC/DC0%0/2
$err and $stderr =~ /: invalid password$/
$err $stderr =~ /: invalid password$/
Truth table0%0/3
A and B
A= $errB= $stderr =~ /: invalid password$/
ABresult
0X0
100
111
251 #$log->tracef("D1");
252 0 unlink $tempf; # just to make sure
253 0 next PASSWORD;
254 } elsif ($err) {
255 #$log->tracef("D2");
256 0 $stderr =~ s/\R//g;
257 0 $envres->add_result(500, $stderr, {item_id=>$f});
258 0 next FILE;
259 }
260 0 last;
261 }
262 0 ▶ unless (-f $tempf) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $tempf) 0 0 0
263 0 $envres->add_result(412, "No passwords can be successfully used on $f", {item_id=>$f});
264 0 next FILE;
265 }
266  
267 BACKUP:
268 {
269 0 ▶ last unless $args{backup};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"backup"} 0 0 0
270 0 ▶ unless (rename $f, "$f~") {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $f, "$f~") 0 0 0
271 0 warn "Can't backup original '$f' to '$f~': $!, skipped backup\n";
272 0 last;
273 };
274 }
275 0 ▶ unless (rename $tempf, $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $tempf, $f) 0 0 0
276 0 $envres->add_result(500, "Can't rename $tempf to $f: $!", {item_id=>$f});
277 0 next FILE;
278 }
279 0 $envres->add_result(200, "OK", {item_id=>$f});
280 }
281  
282 0 $envres->as_struct;
283 }
284  
285 $SPEC{pdf_has_password} = {
286 1 v => 1.1,
287 summary => 'Check if PDF file has password',
288 description => <<'MARKDOWN',
289  
290 This is a wrapper for `qpdf --check`. The wrapper offers additional options like
291 `--quiet``.
292  
293 MARKDOWN
294 args => {
295 %argspec0_file,
296 %argspecopt_quiet,
297 },
298 deps => {
299 prog => 'qpdf',
300 },
301 };
302 0 ▶sub pdf_has_password {
Subroutine pdf_has_password: not called CC=10 SCAR=47.0
Pod documented
303 0 require IPC::System::Options;
304  
305 0 my %args = @_;
306  
307 0 my ($stdout, $stderr);
308 IPC::System::Options::system(
309 {log => 1, fail_log_level => 'info', capture_stdout => \$stdout, capture_stderr => \$stderr},
310 0 "qpdf", "--check", $args{file});
311 0 my $has_password;
312 0 ▶ if ($? && $stderr =~ /: invalid password/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($? and $stderr =~ /: invalid password/) { } 0 0 0
elsif (not $? and $stdout =~ /is not encrypted/) { } 0 0 0
Condition0%0/3
$? and $stderr =~ /: invalid password/
!ll&&!rl&&r
000
MC/DC0%0/2
$? and $stderr =~ /: invalid password/
$? $stderr =~ /: invalid password/
Truth table0%0/3
A and B
A= $?B= $stderr =~ /: invalid password/
ABresult
0X0
100
111
313 0 $has_password = 1;
314 ▶ } elsif (!$? && $stdout =~ /is not encrypted/) {
Condition0%0/3
not $? and $stdout =~ /is not encrypted/
!ll&&!rl&&r
000
MC/DC0%0/2
not $? and $stdout =~ /is not encrypted/
not $? $stdout =~ /is not encrypted/
Truth table0%0/3
not(A) and B
A= not $?B= $stdout =~ /is not encrypted/
ABresult
0X0
100
111
315 0 $has_password = 0;
316 }
317  
318 [200, "OK",
319 0 ▶ $args{quiet} ? "" : ($has_password ? "PDF has password" : defined($has_password) ? "PDF DOES NOT have password" : "CANNOT determine if PDF has password"),
Branch: 5 branches
BranchTrueFalseTotal
$args{'quiet'} ? : 0 0 0
$has_password ? : 0 0 0
defined $has_password ? : 0 0 0
$has_password ? : 0 0 0
defined $has_password ? : 0 0 0
320 {
321 'cmdline.exit_code' => $has_password ? 0 : defined($has_password) ? 1 : 2,
322 }];
323 }
324  
325 $SPEC{convert_pdf_to_text} = {
326 1 v => 1.1,
327 summary => 'Convert PDF file to text',
328 description => <<'MARKDOWN',
329  
330 This utility uses one of the following backends:
331  
332 * pdftotext
333  
334 as well as optionally uses <prog:pdftk> to manipulate PDF, and <prog:fmt> to
335 format text. It offers some options and conveniences like page ranges, output
336 file specification, whether to overwrite existing files, etc.
337  
338 TODO: add ocrmypdf as backend.
339  
340 MARKDOWN
341 args => {
342 %argspec0_file,
343 %argspecopt1_output,
344 %argspecopt_overwrite,
345 %argspecopt_return_output_file,
346 pages => {
347 summary => 'Only convert a range of pages',
348 schema => 'uint_range*',
349 },
350 fmt => {
351 summary => 'Run Unix fmt over the txt output',
352 schema => 'bool*',
353 },
354 raw => {
355 summary => 'If set to true, will run pdftotext with -raw option',
356 schema => 'bool*',
357 },
358 },
359 };
360 0 ▶sub convert_pdf_to_text {
Subroutine convert_pdf_to_text: not called CC=21 SCAR=61.4
Pod documented
361 0 my %args = @_;
362  
363 0 require File::Copy;
364 0 require File::Temp;
365 0 require File::Temp::MoreUtils;
366 0 require File::Which;
367 0 require IPC::System::Options;
368  
369 USE_PDFTOTEXT: {
370 0 ▶ File::Which::which("pdftotext") or do {
Branch: 1 branch
BranchTrueFalseTotal
File::Which::which("pdftotext") or do { log_debug("pdftotext is not in PATH, skipped trying to use pdftotext"); last } 0 0 0
371 0 log_debug "pdftotext is not in PATH, skipped trying to use pdftotext";
372 0 last;
373 };
374  
375 0 my $input_file = $args{file};
376 0 ▶ $input_file =~ /(.+)\.(\w+)\z/ or return [412, "Please supply input file with extension in its name (e.g. foo.pdf instead of foo)"];
Branch: 1 branch
BranchTrueFalseTotal
$input_file =~ /(.+)\.(\w+)\z/ or return [412, "Please supply input file with extension in its name (e.g. foo.pdf instead of foo)"] 0 0 0
377 0 my ($name, $ext) = ($1, $2);
378 0 ▶ $ext =~ /\Ate?xt\z/i and return [304, "Input file '$input_file' is already text"];
Branch: 1 branch
BranchTrueFalseTotal
$ext =~ /\Ate?xt\z/i and return [304, "Input file '${input_file}' is already text"] 0 0 0
379 0 my $output_file = $args{output};
380  
381 0 ▶ if (defined $output_file && -e $output_file && !$args{overwrite}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_file and -e $output_file and not $args{"overwrite"}) 0 0 0
Condition0%0/6
defined $output_file and -e $output_file and not $args{"overwrite"}
!ll&&!rl&&r
000
defined $output_file and -e $output_file
!ll&&!rl&&r
000
MC/DC0%0/3
defined $output_file and -e $output_file and not $args{"overwrite"}
defined $output_file -e $output_file not $args{"overwrite"}
Truth table0%0/4
A and B and not(C)
A= defined $output_fileB= -e $output_fileC= not $args{"overwrite"}
ABCresult
0XX0
10X0
1100
1111
382 0 return [412, "Output file '$output_file' already exists, not overwriting (use --overwrite (-O) to overwrite)"];
383 }
384  
385 0 my $tempdir = File::Temp::tempdir(CLEANUP => !$args{return_output_file});
386 0 my ($temp_fh, $temp_file) = File::Temp::MoreUtils::tempfile_named(name=>$input_file, dir=>$tempdir);
387 0 (my $temp_out_file = $temp_file) =~ s/\.\w+\z/.txt/;
388  
389 0 ▶ if (defined $args{pages}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'pages'}) { } 0 0 0
390 0 ▶ File::Which::which("pdftk")
Branch: 1 branch
BranchTrueFalseTotal
File::Which::which("pdftk") or return [412, "pdftk is required to extract page range from PDF"] 0 0 0
391 or return [412, "pdftk is required to extract page range from PDF"];
392 IPC::System::Options::system(
393 {die=>1, log=>1},
394 0 "pdftk", $input_file, "cat", $args{pages}, "output", $temp_file);
395 } else {
396 0 ▶ File::Copy::copy($input_file, $temp_file) or do {
Branch: 1 branch
BranchTrueFalseTotal
File::Copy::copy($input_file, $temp_file) or do { return [500, "Can't copy '${input_file}' to '${temp_file}': $!"] } 0 0 0
397 0 return [500, "Can't copy '$input_file' to '$temp_file': $!"];
398 };
399 }
400  
401 EXTRACT_PAGE_RANGE: {
402 0 ▶ last unless defined $args{pages};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"pages"} 0 0 0
403  
404 }
405  
406 IPC::System::Options::system(
407 {die=>1, log=>1},
408 0 ▶ "pdftotext", ($args{raw} ? ("-raw") : ()),
Branch: 1 branch
BranchTrueFalseTotal
$args{'raw'} ? : 0 0 0
409 $temp_file, $temp_out_file);
410  
411 FMT: {
412 0 ▶ last unless $args{fmt};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"fmt"} 0 0 0
413 0 ▶ return [412, "fmt is not in PATH"] unless File::Which::which("fmt");
Branch: 1 branch
BranchTrueFalseTotal
unless File::Which::which("fmt") 0 0 0
414 0 my $stdout;
415 0 IPC::System::Options::system(
416 {die=>1, log=>1, capture_stdout=>\$stdout},
417 "fmt", $temp_out_file,
418 );
419 0 ▶ open my $fh, ">" , "$temp_out_file.fmt" or return [500, "Can't open '$temp_out_file.fmt': $!"];
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", "$temp_out_file.fmt" or return [500, "Can't open '$temp_out_file.fmt': $!"] 0 0 0
420 0 print $fh $stdout;
421 0 close $fh;
422 0 $temp_out_file .= ".fmt";
423 }
424  
425 0 ▶ if (defined $output_file || $args{return_output_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_file or $args{'return_output_file'}) { } 0 0 0
Condition0%0/3
defined $output_file or $args{"return_output_file"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $output_file or $args{"return_output_file"}
defined $output_file $args{"return_output_file"}
Truth table0%0/3
A or B
A= defined $output_fileB= $args{"return_output_file"}
ABresult
1X1
011
000
426 0 ▶ if (defined $output_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_file) { } 0 0 0
427 0 ▶ File::Copy::copy($temp_out_file, $output_file) or do {
Branch: 1 branch
BranchTrueFalseTotal
File::Copy::copy($temp_out_file, $output_file) or do { return [500, "Can't copy '${temp_out_file}' to '${output_file}': $!"] } 0 0 0
428 0 return [500, "Can't copy '$temp_out_file' to '$output_file': $!"];
429 };
430 } else {
431 0 $output_file = $temp_out_file;
432 }
433 0 ▶ return [200, "OK", $args{return_output_file} ? $output_file : undef];
Branch: 1 branch
BranchTrueFalseTotal
$args{'return_output_file'} ? : 0 0 0
434 } else {
435 0 ▶ open my $fh, "<", $temp_out_file or return [500, "Can't open '$temp_out_file': $!"];
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $temp_out_file or return [500, "Can't open '${temp_out_file}': $!"] 0 0 0
436 0 local $/;
437 0 my $content = <$fh>;
438 0 close $fh;
439 0 return [200, "OK", $content, {"cmdline.skip_format"=>1}];
440 }
441 }
442  
443 0 [412, "No backend available"];
444 }
445  
446 $SPEC{compress_pdf} = {
447 1 v => 1.1,
448 summary => 'Make PDF smaller',
449 description => <<'MARKDOWN',
450  
451 This utility is a wrapper for <prog:gs> (GhostScript) and is equivalent to the
452 following command:
453  
454 % gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf
455  
456 This wrapper offers support for multiple files and automatically naming output
457 `INPUT.compressed.pdf` by default.
458  
459 MARKDOWN
460 args => {
461 %argspec0_files,
462 %argspecopt_overwrite,
463 setting => {
464 schema => ['str*', {
465 in => [
466 'screen',
467 'ebook',
468 'prepress',
469 'printer',
470 'default',
471 ],
472 'x.in.summaries' => [
473 'Has a lower quality and smaller size (72 dpi)',
474 'Has a better quality, but has a slightly larger size (150 dpi)',
475 'Output is of a higher size and quality (300 dpi)',
476 'Output is of a printer type quality (300 dpi)',
477 'Selects the output which is useful for multiple purposes, can cause large PDFS',
478 ],
479 }],
480 default => 'ebook',
481 cmdline_aliases => {s=>{}},
482 },
483 },
484 examples => [
485 {
486 summary => 'Compress foo.pdf into foo.compressed.pdf using default setting (ebook - 150dpi)',
487 test => 0,
488 src => '[[prog]] foo.pdf',
489 src_plang => 'bash',
490 'x.doc.show_result' => 0,
491 },
492 {
493 summary => 'Compress two files with more extreme compression (screen - 72dpi), overwrite existing output',
494 test => 0,
495 src => '[[prog]] -O -s screen foo.pdf bar.pdf',
496 src_plang => 'bash',
497 'x.doc.show_result' => 0,
498 },
499 ],
500 deps => {
501 prog => 'gs',
502 },
503 };
504 0 ▶sub compress_pdf {
Subroutine compress_pdf: not called CC=7 SCAR=40.3
Pod documented
505 0 require IPC::System::Options;
506  
507 0 my %args = @_;
508  
509 0 my $envres = envresmulti();
510  
511 FILE:
512 0 for my $f (@{ $args{files} }) {
513 0 ▶ unless (-f $f) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $f) 0 0 0
514 0 $envres->add_result(404, "File not found", {item_id=>$f});
515 0 next FILE;
516 }
517 0 my $outputf = $f;
518 0 ▶ $outputf =~ s/\.(pdf)\z/.compressed.$1/i or do {
Branch: 1 branch
BranchTrueFalseTotal
$outputf =~ s/\.(pdf)\z/.compressed.$1/i or do { $envres->add_result(500, "Cannot determine output filename", {"item_id", $f}); next FILE } 0 0 0
519 0 $envres->add_result(500, "Cannot determine output filename", {item_id=>$f});
520 0 next FILE;
521 };
522 0 ▶ if ((-f $outputf) && !$args{overwrite}) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $outputf and not $args{"overwrite"}) 0 0 0
Condition0%0/3
-f $outputf and not $args{"overwrite"}
!ll&&!rl&&r
000
MC/DC0%0/2
-f $outputf and not $args{"overwrite"}
-f $outputf not $args{"overwrite"}
Truth table0%0/3
A and not(B)
A= -f $outputfB= not $args{"overwrite"}
ABresult
0X0
100
111
523 0 $envres->add_result(412, "Won't overwrite existing output $outputf", {item_id=>$f});
524 0 next FILE;
525 }
526  
527 IPC::System::Options::system(
528 0 {log => 1},
529 "gs", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4", "-dPDFSETTINGS=/$args{setting}", "-dNOPAUSE", "-dQUIET", "-dBATCH", "-sOutputFile=$outputf", $f,
530 );
531 0 ▶ if ($?) {
Branch: 1 branch
BranchTrueFalseTotal
if ($?) { } 0 0 0
532 0 $envres->add_result(500, "Failed", {item_id=>$f});
533 } else {
534 0 $envres->add_result(200, "OK", {item_id=>$f});
535 }
536 }
537  
538 0 $envres->as_struct;
539 }
540  
541 $SPEC{pdfsplit} = {
542 1 v => 1.1,
543 summary => 'Split PDF into parts by pages',
544 description => <<'MARKDOWN',
545  
546 You can specify the number of parts and the utility will group roughly the same
547 number of pages:
548  
549 % pdfsplit --num-parts=5 990_pages.pdf
550 Creating 990_pages-part1of5_page001_198.pdf ...
551 Creating 990_pages-part2of5_page199_396.pdf ...
552 Creating 990_pages-part3of5_page397_594.pdf ...
553 Creating 990_pages-part4of5_page595_792.pdf ...
554 Creating 990_pages-part5of5_page596_990.pdf ...
555  
556 MARKDOWN
557 args => {
558 %argspec0_file,
559 %argspecopt_overwrite,
560 num_parts => {
561 summary => 'Specify number of parts',
562 schema => 'posint*',
563 cmdline_aliases => {n=>{}},
564 },
565 num_pages_per_part => {
566 summary => 'Specify number of pages per part',
567 schema => 'posint*',
568 cmdline_aliases => {p=>{}},
569 },
570 },
571 examples => [
572 {
573 summary => 'Split a PDF file into 5 roughly equal parts (number of pages)',
574 src => '[[prog]] -n5 somefile.pdf',
575 src_plang => 'bash',
576 test => 0,
577 'x.doc.show_result' => 0,
578 },
579 {
580 summary => 'Split a PDF file into chunks of one-hundred pages each',
581 src => '[[prog]] -p100 somefile.pdf',
582 src_plang => 'bash',
583 test => 0,
584 'x.doc.show_result' => 0,
585 },
586 ],
587 args_rels => {
588 req_one => [qw/num_parts num_pages_per_part/],
589 },
590 deps => {
591 prog => 'pdftk',
592 },
593 };
594 0 ▶sub pdfsplit {
Subroutine pdfsplit: not called CC=9 SCAR=43.6
Pod documented
595 0 require Cwd;
596 0 require File::Temp;
597 0 require IPC::System::Options;
598 0 require List::MoreUtils;
599 0 require List::NSect;
600 0 require Number::Format::FitWidth;
601  
602 0 my %args = @_;
603 0 my $file = $args{file};
604 0 ▶ defined($file) or return [400, "Please specify input file"];
Branch: 1 branch
BranchTrueFalseTotal
defined $file or return [400, "Please specify input file"] 0 0 0
605 0 my $abs_file = Cwd::abs_path($file);
606  
607 0 ▶ my ($file_prefix) = $file =~ /(.+)\.(?:pdf)\z/i
Branch: 1 branch
BranchTrueFalseTotal
my($file_prefix) = $file =~ /(.+)\.(?:pdf)\z/i or return [400, "Input file must end with .pdf"] 0 0 0
608 or return [400, "Input file must end with .pdf"];
609  
610 0 my $tempdir = File::Temp::tempdir(CLEANUP => 1);
611  
612 0 my $num_pages;
613 my @page_pdf;
614 {
615 0 local $CWD = $tempdir;
616 0 IPC::System::Options::system({log=>1, die=>1}, "pdftk", $abs_file, "burst");
617 0 ▶ @page_pdf = glob("*.pdf");
Subroutine BEGIN: called CC=1 SCAR=0.2
618 0 $num_pages = scalar(@page_pdf);
619 }
620  
621 0 my ($num_parts, $num_pages_per_part, @parts_pdf);
622 0 ▶ if (defined $args{num_parts}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'num_parts'}) { } 0 0 0
623 0 $num_parts = $args{num_parts};
624 0 ▶ if ($num_parts > $num_pages) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_parts > $num_pages) 0 0 0
625 0 log_warn "Reducing number of parts from %d to %d because there are just that number of pages", $num_parts, $num_pages;
626 0 $num_parts = $num_pages;
627 }
628 0 @parts_pdf = List::NSect::nsect($num_parts, @page_pdf);
629 } else {
630 0 $num_pages_per_part = $args{num_pages_per_part};
631 0 $num_parts = int($num_pages / $num_pages_per_part);
632 0 ▶ return [412, "Please choose a smaller num_pages_per_part (currently: $args{num_pages_per_part}) because number of pages is just $num_pages"]
Branch: 1 branch
BranchTrueFalseTotal
unless $num_parts >= 1 0 0 0
633 unless $num_parts >= 1;
634 0 my $iter = List::MoreUtils::natatime($num_pages_per_part, @page_pdf);
635 0 ▶ while (my @part_pdf = $iter->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@part_pdf) = &$iter()) 0 0 0
636 0 push @parts_pdf, \@part_pdf;
637 }
638 }
639  
640 0 ▶ return [304, "There will be just one part"] unless $num_parts > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $num_parts > 1 0 0 0
641  
642 0 my $page_num = 1;
643 0 for my $part (1 .. scalar(@parts_pdf)) {
644 my $part_file = sprintf(
645 "%s-part%sof%d_page%s_%s.pdf",
646 $file_prefix,
647 Number::Format::FitWidth::format_fitwidth({zero_prefix=>1, max=>$num_parts}, $part),
648 scalar(@parts_pdf),
649 Number::Format::FitWidth::format_fitwidth({zero_prefix=>1, max=>$num_pages}, $page_num),
650 0 Number::Format::FitWidth::format_fitwidth({zero_prefix=>1, max=>$num_pages}, $page_num + $#{ $parts_pdf[$part-1] }),
651 );
652 0 log_info "Creating part %d of %d: %s ...",
653 $part, scalar(@parts_pdf), $part_file;
654 0 IPC::System::Options::system({log=>1, die=>1}, "pdftk", (map { "$tempdir/$_" } @{ $parts_pdf[$part-1] }), "cat", "output", $part_file);
655 0 $page_num += @{ $parts_pdf[$part-1] };
656 }
657  
658 0 [200];
659 }
660  
661 1 1;
662 # ABSTRACT: Command-line utilities related to PDF files
663  
664 __END__
↑ Summary pdfgrep.pm »