source: gs2-extensions/pdf-box/trunk/java/perllib/plugins/PDFBoxConverter.pm

Last change on this file was 38728, checked in by davidb, 3 months ago

Updated to dynamically add in JPEG2000 jars, if present of the filesystem

File size: 15.0 KB
Line 
1###########################################################################
2#
3# PDFBoxConverter - helper plugin that does pdf document conversion with PDFBox
4#
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 2010 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26package PDFBoxConverter;
27
28use BaseMediaConverter;
29
30use strict;
31no strict 'refs'; # allow filehandles to be variables and viceversa
32no strict 'subs'; # allow barewords (eg STDERR) as function arguments
33
34#use HTML::Entities; # for encoding characters into their HTML entities when PDFBox converts to text
35
36use gsprintf 'gsprintf';
37use FileUtils;
38
39# these two variables mustn't be initialised here or they will get stuck
40# at those values.
41our $pdfbox_conversion_available;
42our $no_pdfbox_conversion_reason;
43
44BEGIN {
45 @PDFBoxConverter::ISA = ('BaseMediaConverter');
46
47 # Check that PDFBox is installed and available on the path
48 $pdfbox_conversion_available = 1;
49 $no_pdfbox_conversion_reason = "";
50
51 if (!defined $ENV{'GEXT_PDFBOX'}) {
52 $pdfbox_conversion_available = 0;
53 $no_pdfbox_conversion_reason = "gextpdfboxnotinstalled";
54 }
55 else {
56 my $gextpb_home = $ENV{'GEXT_PDFBOX'};
57 my $pbajar = &FileUtils::filenameConcatenate($gextpb_home,"lib","java","pdfbox-app.jar");
58
59 if (!-e $pbajar) {
60 &gsprintf(STDERR,"**** Failed to find $pbajar\n");
61 $pdfbox_conversion_available = 0;
62 $no_pdfbox_conversion_reason = "gextpdfboxjarnotinstalled";
63 }
64 else {
65 # test to see if java is in path
66 # Need to run java -version instead of just java, since the %ERRORLEVEL% returned
67 # for `java` (which is checked below for failure of the command) is 0 for JDK 1.6*
68 # while %ERRORLEVEL% is 1 for JDK 1.7*
69 # If `java -version` is run however, %ERRORLEVEL% returned is 0 if java is
70 # installed, regardless of whether the JDK version is 1.6* or 1.7*.
71 my $java = &util::get_java_command();
72
73 my $cmd = "$java -version";
74 if ($ENV{'GSDLOS'} =~ /^windows/i) {
75 $cmd .= " >nul 2>&1"; # java 2>&1 >null or java >null 2>&1 both work (%ERRORLEVEL% is 0)
76 }
77 else {
78 # On Ubuntu, java >/dev/null 2>&1 works,
79 # but java 2>&1 >/dev/null doesn't work: output goes to screen anyway
80 $cmd .= " >/dev/null 2>&1"; # " >/dev/null 2>&1 &" - don't need & at end for Linux Centos anymore (Ubuntu was already fine without it)
81 }
82
83 my $status = system($cmd);
84
85 if ($status != 0) {
86
87 my $error_message = "**** Testing for java\n";
88 $error_message .= "Failed to run: $cmd\n";
89 $error_message .= "Error variable: |$!| and status: $status\n";
90
91 &gsprintf(STDERR, "PDFBoxConverter: $error_message");
92
93 $pdfbox_conversion_available = 0;
94 $no_pdfbox_conversion_reason = "couldnotrunjava";
95 }
96 }
97 }
98
99}
100
101my $arguments = [ ];
102
103my $options = { 'name' => "PDFBoxConverter",
104 'desc' => "{PDFBoxConverter.desc}",
105 'abstract' => "yes",
106 'inherits' => "yes",
107 'args' => $arguments };
108
109sub new {
110 my ($class) = shift (@_);
111 my ($pluginlist,$inputargs,$hashArgOptLists,$auxilary) = @_;
112 push(@$pluginlist, $class);
113
114 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
115 push(@{$hashArgOptLists->{"OptList"}},$options);
116
117
118 my $self = new BaseMediaConverter($pluginlist, $inputargs,
119 $hashArgOptLists, $auxilary);
120
121 if ($self->{'info_only'}) {
122 # don't worry about any options etc
123 return bless $self, $class;
124 }
125 if ($pdfbox_conversion_available) {
126 my $gextpb_home = $ENV{'GEXT_PDFBOX'};
127 my $pbajar = &FileUtils::filenameConcatenate($gextpb_home,"lib","java","pdfbox-app.jar");
128 my $pb_jbig2_jar = &FileUtils::filenameConcatenate($gextpb_home,"lib","java","jbig2-imageio-3.0.1.jar");
129
130 my $pb_jaicore_jar = &FileUtils::filenameConcatenate($gextpb_home,"lib","java","jai-imageio-core-1.4.0.jar");
131 my $pb_jaijpeg2000_jar = &FileUtils::filenameConcatenate($gextpb_home,"lib","java","jai-imageio-jpeg2000-1.4.0.jar");
132
133 # Not including the following JPEG2000 jar, as it is under commercial license:
134 # https://github.com/jai-imageio/jai-imageio-jpeg2000 leading to https://bintray.com/jai-imageio/maven/jai-imageio-jpeg2000# (Files tab)
135 # my $pbjp2jar = &FileUtils::filenameConcatenate($gextpb_home,"lib","java","jai-imageio-jpeg2000-1.3.0.jar"); # jpeg2000
136
137 my $java = &util::get_java_command();
138 $self->{'pdfbox_txt_launch_cmd'} = "$java -cp \"$pbajar\" org.apache.pdfbox.tools.ExtractText";
139 $self->{'pdfbox_html_launch_cmd'} = "$java -cp \"$pbajar\" -Dline.separator=\"<br />\" org.apache.pdfbox.tools.ExtractText";
140
141 # We use this next cmd to launch our new custom PDFBox class (PDFBoxToImagesAndText.java) to convert each PDF page into an image (gif, jpg, png)
142 # AND its extracted text. Or just each page's extracted text. An item file is still generated,
143 # but this time referring to txtfiles too, not just the images. Result: searchable paged output.
144 # Our new custom class PDFBoxToImagesAndText.java lives in the new build folder, so add that to the classpath for the launch cmd
145 my $pdfbox_build = &FileUtils::filenameConcatenate($gextpb_home,"build");
146 # put the pdfbox jar, the jbig2-imageio library (Apache Software License 2.0)
147 # and our build folder containing our custom PDFBox class on the classpath
148 my $classpath = &util::pathname_cat($pbajar, $pb_jbig2_jar);
149
150 if(!&FileUtils::filenameExists($pb_jaicore_jar)) {
151 $classpath = &util::pathname_cat($classpath, $pb_jaicore_jar);
152 }
153 if(!&FileUtils::filenameExists($pb_jaijpeg2000_jar)) {
154 $classpath = &util::pathname_cat($classpath, $pb_jaijpeg2000_jar);
155 }
156 $classpath = &util::pathname_cat($classpath, $pdfbox_build);
157
158# $self->{'pdfbox_img_launch_cmd'} = "java -cp \"$classpath\" org.apache.pdfbox.tools.PDFToImage"; # pdfbox 2.09 cmd for converting each PDF page to an image (jpg, png)
159 $self->{'pdfbox_imgtxt_launch_cmd'} = "java -cp \"$classpath\" org.greenstone.pdfbox.PDFBoxToImagesAndText";
160 }
161 else {
162 $self->{'no_pdfbox_conversion_reason'} = $no_pdfbox_conversion_reason;
163
164 my $outhandle = $self->{'outhandle'};
165 &gsprintf($outhandle, "PDFBoxConverter: {PDFBoxConverter.noconversionavailable} ({PDFBoxConverter.$no_pdfbox_conversion_reason})\n");
166 }
167
168 $self->{'pdfbox_conversion_available'} = $pdfbox_conversion_available;
169
170 return bless $self, $class;
171
172}
173
174sub init {
175 my $self = shift(@_);
176 my ($verbosity, $outhandle, $failhandle) = @_;
177
178 $self->{'pbtmp_file_paths'} = ();
179}
180
181sub deinit {
182 my $self = shift(@_);
183
184 $self->clean_up_temporary_files();
185}
186
187
188sub convert {
189 my $self = shift(@_);
190 my ($source_file_full_path, $target_file_type) = @_;
191
192 return 0 unless $pdfbox_conversion_available;
193 # check the filename
194 return 0 if ( !-f $source_file_full_path);
195
196 # Although PDFBoxConverter inherits from AutoLoadConverters and therefore
197 # doesn't go through gsConvert.pl, still set the -pdf_tool flag in convert_options
198 # in case in future PDFBoxConverter no longer inherits from AutoLoadConverters
199 # and ends up going through gsConvert.pl
200 $self->{'convert_options'} .= " -pdf_tool pdfbox";
201
202 my $img_output_mode = 0;
203
204 my $convert_to = $self->{'convert_to'};
205 my $paged_txt_output_mode = ($convert_to =~ /(pagedimgtxt|paged_text)/) ? 1 : 0;
206
207 # the following line is necessary to avoid 'uninitialised variable' error
208 # messages concerning the converted_to member variable when PDFPlugin's
209 # use_sections option is checked.
210 # PDFBox plugin now processes use_sections option, when working with v1.5.0
211 # of the PDFBox jar file (which embeds each page in special <div> tags).
212 if ($target_file_type eq "html") {
213 $self->{'converted_to'} = "HTML";
214 } elsif ($target_file_type eq "jpg" || $target_file_type eq "png") { # || $target_file_type eq "gif"
215 # GIF not supported by PDFBox at present, see https://pdfbox.apache.org/1.8/commandline.html#pdftoimage
216 $self->{'converted_to'} = $target_file_type;
217 $img_output_mode = 1;
218 } else {
219 $self->{'converted_to'} = "text";
220 }
221
222 my $outhandle = $self->{'outhandle'};
223 my $verbosity = $self->{'verbosity'};
224
225 my $source_file_no_path = &File::Basename::basename($source_file_full_path);
226 # Determine the full name and path of the output file
227 my $target_file_path;
228
229 if ($self->{'enable_cache'}) {
230 $self->init_cache_for_file($source_file_full_path);
231 my $cache_dir = $self->{'cached_dir'}; # full path to cache dir and file_root subdir inside it
232 my $file_root = $self->{'cached_file_root'}; # just the name of file_root subdir
233 #$file_root .= "_$convert_id" if ($convert_id ne "");
234
235 # append the output filetype suffix only for non-image output formats, since for
236 # images we can be outputting multiple image files per single PDF input file
237 #my $target_file = ($img_output_mode || $paged_txt_output_mode) ? "" : "$file_root.$target_file_type";
238 my $target_file = ($img_output_mode || $paged_txt_output_mode) ? "pages" : "$file_root.$target_file_type";
239
240 $target_file_path = &FileUtils::filenameConcatenate($cache_dir,$target_file);
241
242 if($img_output_mode || $paged_txt_output_mode) {
243 if(!&FileUtils::directoryExists($target_file_path)) {
244 mkdir($target_file_path);
245 }
246 }
247
248 # In this branch of the if-statement, we *don't* want this stored as part of 'pbtmp_file_path'
249 }
250 else {
251 # this is in gsdl/tmp. get a tmp filename in collection instead???
252 $target_file_path = &util::get_tmp_filename($target_file_type);
253
254 # for image files, remove the suffix, since we can have many output image files
255 # per input PDF (one img for each page of the PDF, for example)
256 if($img_output_mode || $paged_txt_output_mode) {
257 $target_file_path =~ s/\.[^.]*$//g;
258
259 if(!&FileUtils::directoryExists($target_file_path)) {
260 mkdir($target_file_path);
261 }
262
263 # once the item file for the imgs has been created, need to adjust target_file_path
264
265 # below, we'll store the dir just created to pbtmp_file_paths, so all imgs and the
266 # item file generated in it can be deleted in one go on clean_up
267 }
268
269 push(@{$self->{'pbtmp_file_paths'}}, $target_file_path);
270 }
271
272 # Generate and run the convert command
273 my $convert_cmd = "";
274
275 # want the filename without extension, because any images
276 # are to be generated with the same filename as the PDF
277 my ($tailname, $dirname, $suffix) = &File::Basename::fileparse($source_file_full_path, "\\.[^\\.]+\$");
278
279 if($img_output_mode || $paged_txt_output_mode) { # converting each page to image and/or text
280 my $output_prefix = &FileUtils::filenameConcatenate($target_file_path, $tailname);
281
282 # Our custom class does renaming of the pages (simplified to just numbers) for PagedImagePlugin
283 #$convert_cmd = $paged_txt_output_mode ? $self->{'pdfbox_imgtxt_launch_cmd'} : $self->{'pdfbox_img_launch_cmd'};
284 $convert_cmd = $self->{'pdfbox_imgtxt_launch_cmd'};
285 $convert_cmd .= " -imagesOnly" unless($paged_txt_output_mode); # set to images only unless there's text too
286 if($img_output_mode) { # whether images-only or images-and-text mode
287 $convert_cmd .= " -imageType $target_file_type";
288 $convert_cmd .= " -dpi ". $self->{"dpi"} if defined $self->{"dpi"};
289 } else { # img_output_mode off, so paged txt only and no images
290 $convert_cmd .= " -textOnly";
291 }
292
293 $convert_cmd .= " -outputPrefix \"$output_prefix\"";
294 $convert_cmd .= " \"$source_file_full_path\"";
295
296 } else { # single stream of text or html
297
298 if ($target_file_type eq "html") {
299 $convert_cmd = $self->{'pdfbox_html_launch_cmd'};
300 $convert_cmd .= " -html" if ($target_file_type eq "html");
301 } else {
302 $convert_cmd = $self->{'pdfbox_txt_launch_cmd'};
303 }
304 $convert_cmd .= " \"$source_file_full_path\" \"$target_file_path\"";
305 }
306
307 if ($verbosity>2) {
308 &gsprintf($outhandle,"Convert command: $convert_cmd\n");
309 }
310
311 my $print_info = { 'message_prefix' => "PDFBox Conversion",
312 'message' => "Converting $source_file_no_path to: $target_file_type" };
313 # $print_info->{'cache_mode'} = $cache_mode if ($cache_mode ne "");
314
315 my ($regenerated,$result,$had_error)
316 = $self->autorun_general_cmd($convert_cmd,$source_file_full_path, $target_file_path,$print_info);
317
318 if($img_output_mode || $paged_txt_output_mode) {
319 # now the images have been generated, generate the "$target_file_path/tailname.item"
320 # item file for them, which is also the target_file_path that needs to be returned
321 $target_file_path = &util::create_itemfile($target_file_path, $tailname, $target_file_type);
322 #print STDERR "**** item file: $target_file_path\n";
323 }
324 elsif ($self->{'converted_to'} eq "text") {
325 # ensure html entities are doubly escaped for pdfbox to text conversion: &amp; -> &amp;amp;
326 # conversion to html does it automatically, but conversion to text doesn't
327 # and this results in illegal characters in doc.xml
328
329 my $fulltext = &FileUtils::readUTF8File($target_file_path);
330 if(defined $fulltext) {
331 #$fulltext = &HTML::Entities::encode($fulltext); # doesn't seem to help
332 $fulltext =~ s@&@&amp;@sg; # Kathy's fix to ensure doc contents don't break XML
333 &FileUtils::writeUTF8File($target_file_path, \$fulltext);
334 } else {
335 print STDERR "PDFBoxConverter::convert(): Unable to read from converted file\n";
336 $had_error = 1;
337 }
338 }
339
340 if ($had_error) {
341 return (0, $result,$target_file_path);
342 }
343 return (1, $result,$target_file_path);
344}
345
346sub convert_without_result {
347 my $self = shift(@_);
348
349 my $source_file_path = shift(@_);
350 my $target_file_type = shift(@_);
351 my $convert_options = shift(@_) || "";
352 my $convert_id = shift(@_) || "";
353
354 return $self->convert($source_file_path,$target_file_type,
355 $convert_options,$convert_id,"without_result");
356}
357
358sub clean_up_temporary_files {
359 my $self = shift(@_);
360
361 foreach my $pbtmp_file_path (@{$self->{'pbtmp_file_paths'}}) {
362 if (-d $pbtmp_file_path) {
363 #print STDERR "@@@@@@ cleanup called on $pbtmp_file_path\n";
364 &FileUtils::removeFilesRecursive($pbtmp_file_path);
365 }
366 elsif (-e $pbtmp_file_path) {
367 &FileUtils::removeFiles($pbtmp_file_path);
368 }
369 }
370
371 $self->{'pbtmp_file_paths'} = ();
372}
373
374
3751;
Note: See TracBrowser for help on using the repository browser.