root/main/trunk/greenstone2/perllib/plugins/PDFv1Plugin.pm @ 32303

Revision 32303, 14.9 KB (checked in by ak19, 13 months ago)

Forgot to update the plugin descriptions for the PDF plugins.

Line 
1###########################################################################
2#
3# PDFv1Plugin.pm -- The older pdf plugin, which uses the older pdftohtml
4# tool that can't handle newer versions of PDFs.
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) 1999-2018 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 PDFv1Plugin;
27
28use strict;
29no strict 'refs'; # so we can use a var for filehandles (e.g. STDERR)
30no strict 'subs'; # allow filehandles to be variables and viceversa
31
32use ConvertBinaryFile;
33use ReadTextFile;
34use unicode;
35
36
37@PDFv1Plugin::ISA = ('ConvertBinaryFile', 'ReadTextFile');
38
39# PDFv1 plugin should be returned to being more like it was before AutoLoadConverters/PDFBox extension's inclusion
40# like the PDFPlugin was at http://trac.greenstone.org/browser/main/trunk/greenstone2/perllib/plugins/PDFPlugin.pm?rev=22597
41my $convert_to_list =
42    [ { 'name' => "auto",
43    'desc' => "{ConvertBinaryFile.convert_to.auto}" },
44      { 'name' => "html",
45    'desc' => "{ConvertBinaryFile.convert_to.html}" },
46      { 'name' => "text",
47    'desc' => "{ConvertBinaryFile.convert_to.text}" },     
48      { 'name' => "pagedimg_jpg",
49    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_jpg}"},
50      { 'name' => "pagedimg_gif",
51    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_gif}"},
52      { 'name' => "pagedimg_png",
53    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_png}"},
54      ];
55
56
57my $arguments =
58    [
59     { 'name' => "convert_to",
60       'desc' => "{ConvertBinaryFile.convert_to}",
61       'type' => "enum",
62       'reqd' => "yes",
63       'list' => $convert_to_list,
64       'deft' => "html" },   
65     { 'name' => "process_exp",
66       'desc' => "{BaseImporter.process_exp}",
67       'type' => "regexp",
68       'deft' => &get_default_process_exp(),
69       'reqd' => "no" },
70     { 'name' => "block_exp",
71       'desc' => "{CommonUtil.block_exp}",
72       'type' => "regexp",
73       'deft' => &get_default_block_exp() },
74     { 'name' => "metadata_fields",
75       'desc' => "{HTMLPlugin.metadata_fields}",
76       'type' => "string",
77       'deft' => "Title,Author,Subject,Keywords" },
78      { 'name' => "metadata_field_separator",
79    'desc' => "{HTMLPlugin.metadata_field_separator}",
80    'type' => "string",
81    'deft' => "" },
82     { 'name' => "noimages",
83       'desc' => "{PDFPlugin.noimages}",
84       'type' => "flag" },
85     { 'name' => "allowimagesonly",
86       'desc' => "{PDFPlugin.allowimagesonly}",
87       'type' => "flag" },
88     { 'name' => "complex",
89       'desc' => "{PDFPlugin.complex}",
90       'type' => "flag" },
91     { 'name' => "nohidden",
92       'desc' => "{PDFPlugin.nohidden}",
93       'type' => "flag" },
94     { 'name' => "zoom",
95       'desc' => "{PDFv1Plugin.zoom}",
96       'deft' => "2",
97       'range' => "1,3", # actually the range is 0.5-3
98       'type' => "int" },
99     { 'name' => "use_sections",
100       'desc' => "{PDFPlugin.use_sections}",
101       'type' => "flag" },
102     { 'name' => "description_tags",
103       'desc' => "{HTMLPlugin.description_tags}",
104       'type' => "flag" },
105      { 'name' => "use_realistic_book",
106        'desc' => "{PDFPlugin.use_realistic_book}",
107    'type' => "flag"}
108     ];
109
110my $options = { 'name'     => "PDFv1Plugin",
111        'desc'     => "{PDFv1Plugin.desc}",
112        'abstract' => "no",
113        'inherits' => "yes",
114        'srcreplaceable' => "yes", # Source docs in PDF can be replaced with GS-generated html     
115        'args'     => $arguments };
116
117sub new {
118    my ($class) = shift (@_);
119    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
120    push(@$pluginlist, $class);
121
122    push(@$inputargs,"-title_sub");
123    push(@$inputargs,'^(Page\s+\d+)?(\s*1\s+)?');
124
125    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
126    push(@{$hashArgOptLists->{"OptList"}},$options);
127
128    my $self = new ConvertBinaryFile($pluginlist, $inputargs, $hashArgOptLists);
129   
130    if ($self->{'info_only'}) {
131    # don't worry about any options etc
132    return bless $self, $class;
133    }
134   
135    $self = bless $self, $class;
136    $self->{'file_type'} = "PDF";
137
138    # these are passed through to gsConvert.pl by ConvertBinaryFile.pm
139    my $zoom = $self->{"zoom"};
140    $self->{'convert_options'} = "-pdf_tool pdftohtml"; # PDFPluginv1 only ever uses the old pdftohtml conversion tool
141    $self->{'convert_options'} .= " -pdf_zoom $zoom";
142    $self->{'convert_options'} .= " -pdf_complex" if $self->{"complex"};
143    $self->{'convert_options'} .= " -pdf_nohidden" if $self->{"nohidden"};
144    $self->{'convert_options'} .= " -pdf_ignore_images" if $self->{"noimages"};
145    $self->{'convert_options'} .= " -pdf_allow_images_only" if $self->{"allowimagesonly"};
146
147    # check convert_to
148    if ($self->{'convert_to'} eq "text" && $ENV{'GSDLOS'} =~ /^windows$/i) {
149    &gsprintf::gsprintf(STDERR, "{PDFv1Plugin.win_old_pdftotext_unsupported}\n");
150    $self->{'convert_to'} = "html";
151    }
152    elsif ($self->{'convert_to'} eq "auto") {
153    # choose html ?? is this the best option
154    $self->{'convert_to'} = "html";
155    }
156    if ($self->{'use_realistic_book'}) {
157    if ($self->{'convert_to'} ne "html") {
158        print STDERR "PDFs will be converted to HTML for realistic book functionality\n";
159        $self->{'convert_to'} = "html";
160    }
161    }
162    # set convert_to_plugin and convert_to_ext
163    $self->set_standard_convert_settings();
164
165    my $secondary_plugin_name = $self->{'convert_to_plugin'};
166    my $secondary_plugin_options = $self->{'secondary_plugin_options'};
167
168    if (!defined $secondary_plugin_options->{$secondary_plugin_name}) {
169    $secondary_plugin_options->{$secondary_plugin_name} = [];
170    }
171    my $specific_options = $secondary_plugin_options->{$secondary_plugin_name};
172
173    # following title_sub removes "Page 1" added by pdftohtml, and a leading
174    # "1", which is often the page number at the top of the page. Bad Luck
175    # if your document title actually starts with "1 " - is there a better way?
176    push(@$specific_options , "-title_sub", '^(Page\s+\d+)?(\s*1\s+)?');
177    my $associate_tail_re = $self->{'associate_tail_re'};
178    if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
179    push(@$specific_options, "-associate_tail_re", $associate_tail_re);
180    }
181    push(@$specific_options, "-file_rename_method", "none");
182   
183    if ($secondary_plugin_name eq "HTMLPlugin") {
184    # pdftohtml always produces utf8
185    push(@$specific_options, "-input_encoding", "utf8");
186    push(@$specific_options, "-extract_language") if $self->{'extract_language'};
187    push(@$specific_options, "-processing_tmp_files");
188    # Instruct HTMLPlug (when eventually accessed through read_into_doc_obj)
189    # to extract these metadata fields from the HEAD META fields
190    if (defined $self->{'metadata_fields'} && $self->{'metadata_fields'} =~ /\S/) {
191        push(@$specific_options,"-metadata_fields",$self->{'metadata_fields'});
192    } else {
193        push(@$specific_options,"-metadata_fields","Title,GENERATOR,date,author<Creator>");
194    }
195    if (defined $self->{'metadata_field_separator'} && $self->{'metadata_field_separator'} =~ /\S/) {
196        push(@$specific_options,"-metadata_field_separator",$self->{'metadata_field_separator'});
197    }
198    if ($self->{'use_sections'} || $self->{'description_tags'}) {
199        $self->{'description_tags'} = 1;
200        push(@$specific_options, "-description_tags");
201    }
202    if ($self->{'use_realistic_book'}) {
203        push(@$specific_options, "-use_realistic_book");
204    }
205    }
206    elsif ($secondary_plugin_name eq "PagedImagePlugin") {
207    push(@$specific_options, "-screenviewsize", "1000");
208    push(@$specific_options, "-enable_cache");
209    push(@$specific_options, "-processing_tmp_files");
210    }
211
212    $self = bless $self, $class; # Q TODO: why does it do this a 2nd time in this function?
213    $self->load_secondary_plugins($class,$secondary_plugin_options,$hashArgOptLists);
214    return $self;
215}
216
217sub get_default_process_exp {
218    my $self = shift (@_);
219
220    return q^(?i)\.pdf$^;
221}
222
223# so we don't inherit HTMLPlug's block exp...
224sub get_default_block_exp {
225    return "";
226}
227
228 
229# By setting hashing to be on ga xml this ensures that two
230# PDF files that are identical except for the metadata
231# to hash to different values. Without this, when each PDF
232# file is converted to HTML there is a chance that they
233# will both be *identical* if the conversion utility does
234# not embed the metadata in the generated HTML. This is
235# certainly the case when PDFBOX is being used.
236
237# This change makes this convert to based plugin more
238# consistent with the original vision that the same document
239# with different metadata should
240# be seen as different.
241
242sub get_oid_hash_type {
243    my $self = shift (@_);
244    return "hash_on_ga_xml";
245}
246 
247 
248#sub tmp_area_convert_file {
249#
250#    my $self = shift (@_);
251#    return $self->AutoLoadConverters::tmp_area_convert_file(@_);
252#
253#}
254
255sub convert_post_process
256{
257    my $self = shift (@_);
258    my ($conv_filename) = @_;
259
260    my $outhandle=$self->{'outhandle'};
261
262    #$self->{'input_encoding'} = "utf8"; # The output is always in utf8 (is it?? it is for html, but what about other types?)
263    #my ($language, $encoding) = $self->textcat_get_language_encoding ($conv_filename);
264
265    # read in file ($text will be in utf8)
266    my $text = "";
267    # encoding will be utf8 for html files - what about other types? will we do this step for them anyway?
268    $self->read_file ($conv_filename, "utf8", "", \$text);
269
270    # Clean html from low and high surrogates D800–DFFF
271    $text =~ s@[\N{U+D800}-\N{U+DFFF}]@\ @g;
272   
273    # Calculate number of pages based on <a ...> tags (we have a <a name=1> etc
274    # for each page).  Metadata based on this calculation not set until process()
275    #
276    # Note: this is done even if we are not breaking the document into pages as it might
277    # be useful to give an indication of document length in browser through setting
278    # num_pages as metadata.
279    my @pages = ($text =~ m/\<[Aa] name=\"?\w+\"?>/ig); #<div style=\"?page-break-before:always; page-break-after:always\"?>
280    my $num_pages = scalar(@pages);
281    $self->{'num_pages'} = $num_pages;
282
283    if ($self->{'use_sections'}
284    && $self->{'converted_to'} eq "HTML") {
285
286    print $outhandle "PDFPlugin: Calculating sections...\n";
287
288    # we have "<a name=1></a>" etc for each page
289    # it may be <A name=
290    my @sections = split('<[Aa] name=', $text);
291
292    my $top_section = "";
293
294    if (scalar (@sections) == 1) { #only one section - no split!
295        print $outhandle "PDFPlugin: warning - no sections found\n";
296    } else {
297        $top_section .= shift @sections; # keep HTML header etc as top_section
298    }
299
300    # handle first section specially for title? Or all use first 100...
301   
302    my $title = $sections[0];
303    $title =~ s/^\"?\w+\"?>//; # specific for pdftohtml...
304    $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
305    $title =~ s/<[^>]*>/ /g;
306    $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
307    $title =~ s/^\s+//s;
308    $title =~ s/\s+$//;
309    $title =~ s/\s+/ /gs;
310    $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
311    $title =~ s/^\s+//s; # in case title_sub introduced any...
312    $title = substr ($title, 0, 100);
313    $title =~ s/\s\S*$/.../;
314
315
316    if (scalar (@sections) == 1) { # no sections found
317        $top_section .= $sections[0];
318        @sections=();
319    } else {
320        $top_section .= "<!--<Section>\n<Metadata name=\"Title\">$title</Metadata>\n-->\n <!--</Section>-->\n";
321    }
322
323    # add metadata per section...
324    foreach my $section (@sections) {
325        # section names are not always just digits, may be like "outline"
326        $section =~ s@^\"?(\w+)\"?></a>@@; # leftover from split expression...
327
328        $title = $1; # Greenstone does magic if sections are titled digits
329        if (! defined($title) ) {
330        print STDERR "no title: $section\n";
331        $title = " "; # get rid of the undefined warning in next line
332        }
333        my $newsection = "<!-- from PDFPlugin -->\n<!-- <Section>\n";
334        $newsection .= "<Metadata name=\"Title\">" . $title
335        . "</Metadata>\n--><br />\n"; #TODO: . "</Metadata>\n--><p>\n";
336        $newsection .= $section;
337        $newsection .= "<!--</Section>-->\n";
338        $section = $newsection;
339    }
340
341    $text=join('', ($top_section, @sections));
342    }
343
344    if ($self->{'use_sections'}
345    && $self->{'converted_to'} eq "text") {
346    print STDERR "**** When converting PDF to text, cannot apply use_sections\n";
347    }
348
349
350    # The following should no longer be needed, now that strings
351    # read in are Unicode aware (in the Perl sense) rather than
352    # raw binary strings that just happen to be UTF-8 compliant
353
354    # turn any high bytes that aren't valid utf-8 into utf-8.
355##    unicode::ensure_utf8(\$text);
356
357    # Write it out again!
358    $self->utf8_write_file (\$text, $conv_filename);
359}
360
361
362# do plugin specific processing of doc_obj for HTML type
363sub process {
364    my $self = shift (@_);
365    my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
366
367    my $result = $self->process_type($base_dir,$file,$doc_obj);
368
369    # fix up the extracted date metadata to be in Greenstone date format,
370    # and fix the capitalisation of 'date'
371    my $cursection = $doc_obj->get_top_section();
372    foreach my $datemeta (@{$doc_obj->get_metadata($cursection, "date")}) {
373    $doc_obj->delete_metadata($cursection, "date", $datemeta);
374
375    # We're just interested in the date bit, not the time
376    # some pdf creators (eg "Acrobat 5.0 Scan Plug-in for Windows")
377    # set a /CreationDate, and set /ModDate to 000000000. pdftohtml
378    # extracts the ModDate, so it is 0...
379    $datemeta =~ /(\d+)-(\d+)-(\d+)/;
380    my ($year, $month, $day) = ($1,$2,$3);
381    if (defined($year) && defined($month) && defined($day)) {
382        if ($year == 0) {next}
383        if ($year < 100) {$year += 1900} # just to be safe
384        if ($month =~ /^\d$/) {$month="0$month"} # single digit
385        if ($day =~ /^\d$/) {$day="0$day"} # single digit
386        my $date="$year$month$day";
387        $doc_obj->add_utf8_metadata($cursection, "Date", $date);
388    }
389    }
390
391    $doc_obj->add_utf8_metadata($cursection, "NumPages", $self->{'num_pages'}) if defined $self->{'num_pages'};
392   
393    if ($self->{'use_sections'} && $self->{'converted_to'} eq "HTML") {
394    # For gs2 we explicitly make it a paged document, cos greenstone won't get it
395    # right if any section has an empty title, or one with letters in it
396    if (&util::is_gs3()) {
397        # but for gs3, paged docs currently use image slider which is ugly if there are no images
398        $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Hierarchy");
399    } else {
400        $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Paged");
401    }
402    }
403
404    return $result;
405}
406
4071;
Note: See TracBrowser for help on using the browser.