source: main/trunk/greenstone2/perllib/plugins/PDFPlugin.pm@ 32290

Last change on this file since 32290 was 32290, checked in by ak19, 6 years ago
  1. Making paged_pretty_html the default rather than pretty_html, since it's likely more users will want their converted PDF sectionalised. 2. Hopefully improved the display strings to make sense for users rather than for me.
  • Property svn:keywords set to Author Date Id Revision
File size: 17.2 KB
RevLine 
[1410]1###########################################################################
2#
[15872]3# PDFPlugin.pm -- reasonably with-it pdf plugin
[1410]4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
[2661]8# Copyright (C) 1999-2001 New Zealand Digital Library Project
[1410]9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
[15872]25package PDFPlugin;
[1410]26
[10353]27use strict;
[22702]28no strict 'refs'; # so we can use a var for filehandles (e.g. STDERR)
[32205]29no strict 'subs'; # allow filehandles to be variables and viceversa
[1410]30
[22705]31use ReadTextFile;
32use unicode;
[22702]33
[22861]34use AutoLoadConverters;
[22864]35use ConvertBinaryFile;
[1410]36
[22861]37@PDFPlugin::ISA = ('ConvertBinaryFile', 'AutoLoadConverters', 'ReadTextFile');
[22705]38
39
[10452]40my $convert_to_list =
41 [ { 'name' => "auto",
[15872]42 'desc' => "{ConvertBinaryFile.convert_to.auto}" },
[10452]43 { 'name' => "html",
[15872]44 'desc' => "{ConvertBinaryFile.convert_to.html}" },
[10452]45 { 'name' => "text",
[15872]46 'desc' => "{ConvertBinaryFile.convert_to.text}" },
[10452]47 { 'name' => "pagedimg_jpg",
[15872]48 'desc' => "{ConvertBinaryFile.convert_to.pagedimg_jpg}"},
[10452]49 { 'name' => "pagedimg_gif",
[15872]50 'desc' => "{ConvertBinaryFile.convert_to.pagedimg_gif}"},
[10452]51 { 'name' => "pagedimg_png",
[15872]52 'desc' => "{ConvertBinaryFile.convert_to.pagedimg_png}"},
[10452]53 ];
54
55
56my $arguments =
[10889]57 [
58 { 'name' => "convert_to",
[15872]59 'desc' => "{ConvertBinaryFile.convert_to}",
[10889]60 'type' => "enum",
61 'reqd' => "yes",
62 'list' => $convert_to_list,
63 'deft' => "html" },
64 { 'name' => "process_exp",
[31492]65 'desc' => "{BaseImporter.process_exp}",
[10889]66 'type' => "regexp",
67 'deft' => &get_default_process_exp(),
68 'reqd' => "no" },
69 { 'name' => "block_exp",
[31494]70 'desc' => "{CommonUtil.block_exp}",
[10889]71 'type' => "regexp",
72 'deft' => &get_default_block_exp() },
73 { 'name' => "metadata_fields",
[15872]74 'desc' => "{HTMLPlugin.metadata_fields}",
[10889]75 'type' => "string",
[24431]76 'deft' => "Title,Author,Subject,Keywords" },
[21800]77 { 'name' => "metadata_field_separator",
78 'desc' => "{HTMLPlugin.metadata_field_separator}",
79 'type' => "string",
80 'deft' => "" },
[10889]81 { 'name' => "noimages",
[15872]82 'desc' => "{PDFPlugin.noimages}",
[10889]83 'type' => "flag" },
84 { 'name' => "allowimagesonly",
[15872]85 'desc' => "{PDFPlugin.allowimagesonly}",
[10889]86 'type' => "flag" },
87 { 'name' => "complex",
[15872]88 'desc' => "{PDFPlugin.complex}",
[10889]89 'type' => "flag" },
90 { 'name' => "nohidden",
[15872]91 'desc' => "{PDFPlugin.nohidden}",
[10889]92 'type' => "flag" },
93 { 'name' => "zoom",
[15872]94 'desc' => "{PDFPlugin.zoom}",
[10889]95 'deft' => "2",
[32289]96 'range' => "1,3", # actually the range is 0.5-3
97 'type' => "int" },
[10889]98 { 'name' => "use_sections",
[15872]99 'desc' => "{PDFPlugin.use_sections}",
[10889]100 'type' => "flag" },
101 { 'name' => "description_tags",
[15872]102 'desc' => "{HTMLPlugin.description_tags}",
[29101]103 'type' => "flag" },
104 { 'name' => "use_realistic_book",
[29102]105 'desc' => "{PDFPlugin.use_realistic_book}",
[29101]106 'type' => "flag"}
[10889]107 ];
[3540]108
[15872]109my $options = { 'name' => "PDFPlugin",
110 'desc' => "{PDFPlugin.desc}",
[6408]111 'abstract' => "no",
[3540]112 'inherits' => "yes",
[15114]113 'srcreplaceable' => "yes", # Source docs in PDF can be replaced with GS-generated html
[3540]114 'args' => $arguments };
115
[1410]116sub new {
[10218]117 my ($class) = shift (@_);
118 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
119 push(@$pluginlist, $class);
[2452]120
[10218]121 push(@$inputargs,"-title_sub");
122 push(@$inputargs,'^(Page\s+\d+)?(\s*1\s+)?');
[5616]123
[15872]124 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
125 push(@{$hashArgOptLists->{"OptList"}},$options);
[10429]126
[22861]127 my $auto_converter_self = new AutoLoadConverters($pluginlist,$inputargs,$hashArgOptLists,["PDFBoxConverter"],1);
128 my $cbf_self = new ConvertBinaryFile($pluginlist, $inputargs, $hashArgOptLists);
[31492]129 my $self = BaseImporter::merge_inheritance($auto_converter_self, $cbf_self);
[10353]130
[10580]131 if ($self->{'info_only'}) {
132 # don't worry about any options etc
133 return bless $self, $class;
134 }
[22861]135
136 $self = bless $self, $class;
[15872]137 $self->{'file_type'} = "PDF";
138
[32273]139 # PDFPlugin is deprecated and migrating users should hereafter choose between
140 # PDFv1Plugin, if they want to use the old pdftohtml tool's capabilities,
141 # and PDFv2Plugin, if they want to use pdfbox or the new xpdftools capabilities.
[32275]142 &gsprintf::gsprintf(STDERR, "{PDFPlugin.deprecated_plugin}\n");
[32273]143
[15872]144 # these are passed through to gsConvert.pl by ConvertBinaryFile.pm
[10218]145 my $zoom = $self->{"zoom"};
[32273]146 # By default, PDFPlugin assumes gsConvert.pl will run the old pdftohtml conversion tool,
147 # But if pdfbox conversion is turned on, the tool used is pdfbox (which is presently an
148 # AutoLoadConverter and therefore bypasses gsConvert.pl)
149 $self->{'convert_options'} = "-pdf_tool pdftohtml";
150 $self->{'convert_options'} .= " -pdf_zoom $zoom";
[10218]151 $self->{'convert_options'} .= " -pdf_complex" if $self->{"complex"};
152 $self->{'convert_options'} .= " -pdf_nohidden" if $self->{"nohidden"};
153 $self->{'convert_options'} .= " -pdf_ignore_images" if $self->{"noimages"};
[10452]154 $self->{'convert_options'} .= " -pdf_allow_images_only" if $self->{"allowimagesonly"};
[3720]155
[22597]156 # check convert_to
157 if ($self->{'convert_to'} eq "text" && $ENV{'GSDLOS'} =~ /^windows$/i) {
[32277]158 &gsprintf::gsprintf(STDERR, "{PDFPlugin.win_old_pdftotext_unsupported}\n");
[32273]159 $self->{'convert_to'} = "html";
[10273]160 }
[22597]161 elsif ($self->{'convert_to'} eq "auto") {
162 # choose html ?? is this the best option
[32289]163 $self->{'convert_to'} = "html";
[10273]164 }
[29101]165 if ($self->{'use_realistic_book'}) {
166 if ($self->{'convert_to'} ne "html") {
[32290]167 &gsprintf::gsprintf(STDERR, "PDFv2Plugin: {PDFPlugin.html_for_realistic_book}\n");
[29101]168 $self->{'convert_to'} = "html";
169 }
170 }
[22597]171 # set convert_to_plugin and convert_to_ext
[22702]172 $self->set_standard_convert_settings();
[18145]173
[22597]174 my $secondary_plugin_name = $self->{'convert_to_plugin'};
175 my $secondary_plugin_options = $self->{'secondary_plugin_options'};
[10273]176
[22597]177 if (!defined $secondary_plugin_options->{$secondary_plugin_name}) {
178 $secondary_plugin_options->{$secondary_plugin_name} = [];
[10724]179 }
[22597]180 my $specific_options = $secondary_plugin_options->{$secondary_plugin_name};
[10429]181
[10273]182 # following title_sub removes "Page 1" added by pdftohtml, and a leading
183 # "1", which is often the page number at the top of the page. Bad Luck
184 # if your document title actually starts with "1 " - is there a better way?
[22597]185 push(@$specific_options , "-title_sub", '^(Page\s+\d+)?(\s*1\s+)?');
[11122]186 my $associate_tail_re = $self->{'associate_tail_re'};
187 if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
[22597]188 push(@$specific_options, "-associate_tail_re", $associate_tail_re);
[11122]189 }
[22597]190 push(@$specific_options, "-file_rename_method", "none");
191
192 if ($secondary_plugin_name eq "HTMLPlugin") {
[22861]193 # pdftohtml always produces utf8 - What about pdfbox???
[24290]194 # push(@$specific_options, "-input_encoding", "utf8");
[22597]195 push(@$specific_options, "-extract_language") if $self->{'extract_language'};
196 push(@$specific_options, "-processing_tmp_files");
197 # Instruct HTMLPlug (when eventually accessed through read_into_doc_obj)
198 # to extract these metadata fields from the HEAD META fields
199 if (defined $self->{'metadata_fields'} && $self->{'metadata_fields'} =~ /\S/) {
200 push(@$specific_options,"-metadata_fields",$self->{'metadata_fields'});
201 } else {
202 push(@$specific_options,"-metadata_fields","Title,GENERATOR,date,author<Creator>");
203 }
204 if (defined $self->{'metadata_field_separator'} && $self->{'metadata_field_separator'} =~ /\S/) {
205 push(@$specific_options,"-metadata_field_separator",$self->{'metadata_field_separator'});
206 }
207 if ($self->{'use_sections'} || $self->{'description_tags'}) {
208 $self->{'description_tags'} = 1;
209 push(@$specific_options, "-description_tags");
210 }
[29101]211 if ($self->{'use_realistic_book'}) {
212 push(@$specific_options, "-use_realistic_book");
213 }
[22597]214 }
215 elsif ($secondary_plugin_name eq "PagedImagePlugin") {
216 push(@$specific_options, "-screenviewsize", "1000");
217 push(@$specific_options, "-enable_cache");
218 push(@$specific_options, "-processing_tmp_files");
219 }
[11122]220
[10273]221 $self = bless $self, $class;
[10429]222 $self->load_secondary_plugins($class,$secondary_plugin_options,$hashArgOptLists);
[10273]223 return $self;
[1410]224}
225
226sub get_default_process_exp {
227 my $self = shift (@_);
228
229 return q^(?i)\.pdf$^;
230}
[2661]231
232# so we don't inherit HTMLPlug's block exp...
233sub get_default_block_exp {
234 return "";
235}
[22861]236
237sub init {
238 my $self = shift (@_);
239
240 # ConvertBinaryFile init
241 $self->SUPER::init(@_);
[23754]242 $self->AutoLoadConverters::init(@_);
[22861]243
244}
245
246sub begin {
247 my $self = shift (@_);
248
[23754]249 $self->AutoLoadConverters::begin(@_);
[22861]250 $self->SUPER::begin(@_);
251
252}
253
254sub deinit {
255 my $self = shift (@_);
[1410]256
[23754]257 $self->AutoLoadConverters::deinit(@_);
[22861]258 $self->SUPER::deinit(@_);
259
260}
261
[24290]262# By setting hashing to be on ga xml this ensures that two
263# PDF files that are identical except for the metadata
264# to hash to different values. Without this, when each PDF
265# file is converted to HTML there is a chance that they
266# will both be *identical* if the conversion utility does
267# not embed the metadata in the generated HTML. This is
268# certainly the case when PDFBOX is being used.
[22861]269
[24290]270# This change makes this convert to based plugin more
271# consistent with the original vision that the same document
272# with different metadata should
273# be seen as different.
274
275sub get_oid_hash_type {
276 my $self = shift (@_);
277 return "hash_on_ga_xml";
278}
279
280
[22861]281sub tmp_area_convert_file {
282
283 my $self = shift (@_);
284 return $self->AutoLoadConverters::tmp_area_convert_file(@_);
285
286}
287
[10273]288sub convert_post_process
289{
[1410]290 my $self = shift (@_);
[10273]291 my ($conv_filename) = @_;
[9465]292
[7019]293 my $outhandle=$self->{'outhandle'};
294
[15963]295 #$self->{'input_encoding'} = "utf8"; # The output is always in utf8 (is it?? it is for html, but what about other types?)
296 #my ($language, $encoding) = $self->textcat_get_language_encoding ($conv_filename);
[8218]297
[10273]298 # read in file ($text will be in utf8)
299 my $text = "";
[15963]300 # encoding will be utf8 for html files - what about other types? will we do this step for them anyway?
301 $self->read_file ($conv_filename, "utf8", "", \$text);
[10273]302
[24159]303 # To support the use_sections option with PDFBox: Greenstone splits PDFs into pages for
304 # sections. The PDFPlugin code wants each new page to be prefixed with <a name=pagenum></a>,
305 # which it then splits on to generate page-based sections. However, that's not what PDFBox
306 # generates in its HTML output. Fortunately, PDFBox does have its own page-separator: it
307 # embeds each page in an extra div. The div opener is:
308 # <div style=\"page-break-before:always; page-break-after:always\">
[24476]309 # The PDFPlugin now looks for this and prefixes <a name=0></a> to each such div. (The
[24159]310 # pagenumber is fixed at 0 since I'm unable to work out how to increment the pagenum during
311 # a regex substitution even with regex extensions on.) Later, when we process each section
312 # to get the pagenum, PDFBox's output for this is pre-processed by having a loopcounter
313 # that increments the pagenum for each subsequent section.
314
315 #$pdfbox_pageheader="\<div style=\"page-break-before:always; page-break-after:always\">";
316 my $loopcounter = 0; # used later on!
317 $text =~ s@\<div style=\"page-break-before:always; page-break-after:always\">@<a name=$loopcounter></a><div style=\"page-break-before:always; page-break-after:always\">@g;
318
319
[10273]320 # Calculate number of pages based on <a ...> tags (we have a <a name=1> etc
321 # for each page). Metadata based on this calculation not set until process()
322 #
[24476]323 # Note: this is done even if we are not breaking the document into pages as it might
[10273]324 # be useful to give an indication of document length in browser through setting
325 # num_pages as metadata.
[30491]326 # Clean html from low and hight surrogates D800–DFFF
[30492]327 $text =~ s@[\N{U+D800}-\N{U+DFFF}]@\ @g;
[24476]328 my @pages = ($text =~ m/\<[Aa] name=\"?\w+\"?>/ig); #<div style=\"?page-break-before:always; page-break-after:always\"?>
[10273]329 my $num_pages = scalar(@pages);
330 $self->{'num_pages'} = $num_pages;
331
[3411]332 if ($self->{'use_sections'}
333 && $self->{'converted_to'} eq "HTML") {
334
[15872]335 print $outhandle "PDFPlugin: Calculating sections...\n";
[3411]336
[3614]337 # we have "<a name=1></a>" etc for each page
[8795]338 # it may be <A name=
[10273]339 my @sections = split('<[Aa] name=', $text);
[3411]340
[10273]341 my $top_section = "";
342
[7019]343 if (scalar (@sections) == 1) { #only one section - no split!
[15872]344 print $outhandle "PDFPlugin: warning - no sections found\n";
[7019]345 } else {
[10273]346 $top_section .= shift @sections; # keep HTML header etc as top_section
[7019]347 }
348
[3411]349 # handle first section specially for title? Or all use first 100...
350
351 my $title = $sections[0];
[8795]352 $title =~ s/^\"?\w+\"?>//; # specific for pdftohtml...
[3411]353 $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
354 $title =~ s/<[^>]*>/ /g;
355 $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
356 $title =~ s/^\s+//s;
357 $title =~ s/\s+$//;
358 $title =~ s/\s+/ /gs;
359 $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
360 $title =~ s/^\s+//s; # in case title_sub introduced any...
361 $title = substr ($title, 0, 100);
362 $title =~ s/\s\S*$/.../;
363
[10273]364
[7019]365 if (scalar (@sections) == 1) { # no sections found
[10273]366 $top_section .= $sections[0];
[7019]367 @sections=();
368 } else {
[10273]369 $top_section .= "<!--<Section>\n<Metadata name=\"Title\">$title</Metadata>\n-->\n <!--</Section>-->\n";
[7019]370 }
[3411]371
372 # add metadata per section...
373 foreach my $section (@sections) {
[8795]374 # section names are not always just digits, may be like "outline"
375 $section =~ s@^\"?(\w+)\"?></a>@@; # leftover from split expression...
[3614]376
[3411]377 $title = $1; # Greenstone does magic if sections are titled digits
[24159]378
379 # A title of pagenum=0 means use_sections is being applied on output from PDFBox,
380 # which didn't originally have a <a name=incremented pagenumber></a> to split each page.
381 # Our Perl code then prefixed <a name=0></a> to it. Now need to increment the pagenum here:
382 if($loopcounter > 0 || ($title eq 0 && $loopcounter == 0)) { # implies use_sections with PDFBox
383 $title = ++$loopcounter;
384 }
385
[3411]386 if (! defined($title) ) {
387 print STDERR "no title: $section\n";
[8795]388 $title = " "; # get rid of the undefined warning in next line
[3411]389 }
[15872]390 my $newsection = "<!-- from PDFPlugin -->\n<!-- <Section>\n";
[3411]391 $newsection .= "<Metadata name=\"Title\">" . $title
[24159]392 . "</Metadata>\n--><br />\n";
[3411]393 $newsection .= $section;
394 $newsection .= "<!--</Section>-->\n";
395 $section = $newsection;
396 }
397
[10273]398 $text=join('', ($top_section, @sections));
[3411]399 }
400
[24199]401 if ($self->{'use_sections'}
402 && $self->{'converted_to'} eq "text") {
403 print STDERR "**** When converting PDF to text, cannot apply use_sections\n";
404 }
[22953]405
[24199]406
[22953]407 # The following should no longer be needed, now that strings
408 # read in are Unicode aware (in the Perl sense) rather than
409 # raw binary strings that just happen to be UTF-8 compliant
410
[8218]411 # turn any high bytes that aren't valid utf-8 into utf-8.
[22953]412## unicode::ensure_utf8(\$text);
[8218]413
[10273]414 # Write it out again!
415 $self->utf8_write_file (\$text, $conv_filename);
416}
[7287]417
418
[10273]419# do plugin specific processing of doc_obj for HTML type
420sub process {
421 my $self = shift (@_);
[15872]422 my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
[7287]423
[15963]424 my $result = $self->process_type($base_dir,$file,$doc_obj);
[10273]425
[8226]426 # fix up the extracted date metadata to be in Greenstone date format,
427 # and fix the capitalisation of 'date'
[8227]428 my $cursection = $doc_obj->get_top_section();
429 foreach my $datemeta (@{$doc_obj->get_metadata($cursection, "date")}) {
[7287]430 $doc_obj->delete_metadata($cursection, "date", $datemeta);
431
432 # We're just interested in the date bit, not the time
[8278]433 # some pdf creators (eg "Acrobat 5.0 Scan Plug-in for Windows")
434 # set a /CreationDate, and set /ModDate to 000000000. pdftohtml
435 # extracts the ModDate, so it is 0...
436 $datemeta =~ /(\d+)-(\d+)-(\d+)/;
437 my ($year, $month, $day) = ($1,$2,$3);
438 if (defined($year) && defined($month) && defined($day)) {
439 if ($year == 0) {next}
440 if ($year < 100) {$year += 1900} # just to be safe
441 if ($month =~ /^\d$/) {$month="0$month"} # single digit
442 if ($day =~ /^\d$/) {$day="0$day"} # single digit
443 my $date="$year$month$day";
444 $doc_obj->add_utf8_metadata($cursection, "Date", $date);
445 }
[7287]446 }
447
[24476]448 $doc_obj->add_utf8_metadata($cursection, "NumPages", $self->{'num_pages'}) if defined $self->{'num_pages'};
[8795]449
450 if ($self->{'use_sections'} && $self->{'converted_to'} eq "HTML") {
[30742]451 # For gs2 we explicitly make it a paged document, cos greenstone won't get it
[8795]452 # right if any section has an empty title, or one with letters in it
[30742]453 if (&util::is_gs3()) {
454 # but for gs3, paged docs currently use image slider which is ugly if there are no images
455 $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Hierarchy");
456 } else {
457 $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Paged");
458 }
[8795]459 }
[10273]460
[7287]461 return $result;
[1410]462}
463
4641;
Note: See TracBrowser for help on using the repository browser.